我在Python中做了一些简单的抓取(使用BeautifulSoup4),但我在检索包含HTML实体的标签时遇到了问题。
这是一个小例子(只删除了真实的URL)
start_url = "..."
next_chapter_bad = "Next Chapter ]>"
next_chapter_good = "Next Chapter ]>"
"""
<td class="comic_navi_right">
<a href="..." class="navi navi-next-chap" title="Next Chapter ]>">Next Chapter ]></a>
<a href="..." class="navi comic-nav-next navi-next" title="Next Page >">Next Page ></a>
<a href="..." class="navi navi-last" title="Most Recent Page >>">Most Recent Page >></a>
</td>
"""
page = requests.get(start_url)
if page.status_code != requests.codes.ok:
return ''
soup = BeautifulSoup(page.text)
# get the url for the "Next chapter" link
next_link = soup.find('a', href=True, string=next_chapter_bad)
print( next_link)
next_link = soup.find('a', href=True, string=next_chapter_good)
print( next_link)
输出结果为:
None
<a class="navi navi-next-chap" href="..." title="Next Chapter ]>">Next Chapter ]></a>
有没有办法让find()与HTML实体一起使用?
答案 0 :(得分:1)
您必须unescape
HTML https://stackoverflow.com/a/2087433/4183498)>
被转义>
。
from HTMLParser import HTMLParser
...
soup = BeautifulSoup(page.text, 'html.parser')
# get the url for the "Next chapter" link
html_parser = HTMLParser()
next_link = soup.find('a', href=True, string=html_parser.unescape(next_chapter_bad))
print( next_link)