Python如何使用re获取网站中的特定代码

标签 python html regex python-2.7 web

我正在尝试对 Python 进行挑战。 http://www.pythonchallenge.com/pc/def/ocr.html 好的。我知道,我可以将源代码中的代码复制粘贴到 txt 文件中,然后制作类似的东西,但我想从网上获取它以提高自己。 (+我已经做了)我试过了

re.findall(r"<!--(.*?)-->,html)

但它没有得到任何东西。 如果你想要我的完整代码在这里:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests,re
link = "http://www.pythonchallenge.com/pc/def/ocr.html"
x = requests.get(link)
codes = re.findall(r"<!--(.*)-->",str(x.content))
print codes 

我也试过这样做:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests,re
link = "http://www.pythonchallenge.com/pc/def/ocr.html"
x = requests.get(link)
codes = re.findall("<!--\n(.*)\n-->",str(x.content))
print codes 

现在它找到了文本,但仍然无法得到那个烂摊子 :(

最佳答案

我会改用 HTML 解析器。你可以find comments在 HTML 中带有 BeautifulSoup .

工作代码:

import requests
from bs4 import BeautifulSoup, Comment


link = "http://www.pythonchallenge.com/pc/def/ocr.html"
response = requests.get(link)

soup = BeautifulSoup(response.content, "html.parser")

code = soup.find_all(text=lambda text: isinstance(text, Comment))[-1]
print(code.strip())

关于Python如何使用re获取网站中的特定代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38249763/

相关文章:

python - 与 Python For 循环速度作斗争

python - Django,找不到网址?

python - ndb 中的游标如何工作?

javascript - 聚焦时如何更改边框宽度

r - gsub 的否定 |替换某个向量中除字符串之外的所有内容

python - 神经网络模型不起作用

javascript - innerHtml 无法在另一个 div 中打印我的 div

javascript - 使用 jQuery 在单击时叠加在图像上

python - 匹配 "without this"

javascript - 使用 !用于正则表达式编号验证