我正在尝试对 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/