1

我在 HTML 中有这样的东西:

<p align="left"><strong><tt>
        some text:</tt></strong><tt> (8/4)</tt><a href="some link"><tt>some other text</tt></a><tt>, (9/4)</tt><a href="some other link"><tt><br/>
        some text:</tt></strong><tt>, (19/6)</tt><!--a href="some link in comment"--><tt>text after comment</tt></p></blockquote></blockquote><tt>, </tt><a href="link i want"><tt>text i want</tt></a><strong><tt><br/>
...
</p>
        

我在 Python 中的代码:

page = requests.get(site)
soup = BeautifulSoup(page.content, 'html.parser')
rounds = soup.find('p', align="left")
matches_links = rounds.find_all('a')

我得到了一些评论和文字的所有链接。之后我什么都得不到</blockquote></blockquote>。这两个块引用在页面代码中是不可见的,只有当我调试我的 Python 代码时,我才能在soup. 在soup我有所有 HTML 代码,但在rounds代码中以<tt>text after comment</tt></p>.

有什么方法可以获得“我想要的链接”和“我想要的文字”?

4

1 回答 1

1

如果您查看 HTML 代码,您会看到</p>之前的</blockquote></blockquote>. 这意味着您的变量rounds不包含您想要的链接。<a>在此<p>标记后搜索下一个:

from bs4 import BeautifulSoup


txt = '''
<p align="left"><strong><tt>
        some text:</tt></strong><tt> (8/4)</tt><a href="some link"><tt>some other text</tt></a><tt>, (9/4)</tt><a href="some other link"><tt><br/>
        some text:</tt></strong><tt>, (19/6)</tt><!--a href="some link in comment"--><tt>text after comment</tt></p></blockquote></blockquote><tt>, </tt><a href="link i want"><tt>text i want</tt></a><strong><tt><br/>
...
</p>
'''

soup = BeautifulSoup(txt, 'html.parser')

matched_link = soup.select_one('p[align="left"] ~ a')
print(matched_link)

印刷:

<a href="link i want"><tt>text i want</tt></a>
于 2020-08-19T10:14:18.333 回答