在BeautifulSoup中使用HTML实体查找

时间:2017-11-02 19:21:26

标签: python html beautifulsoup html-entities

我在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 ]&gt;">Next Chapter ]&gt;</a>
    <a href="..." class="navi comic-nav-next navi-next" title="Next Page &gt;">Next Page &gt;</a>
    <a href="..." class="navi navi-last" title="Most Recent Page &gt;&gt;">Most Recent Page &gt;&gt;</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 ]&gt;">Next Chapter ]&gt;</a>

有没有办法让find()与HTML实体一起使用?

1 个答案:

答案 0 :(得分:1)

您必须unescape HTML https://stackoverflow.com/a/2087433/4183498&gt;被转义>

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)