使用beauthoulsoup通过文本获取Href

2024-04-25 18:25:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我用“requests”和“beautifulsoup”来搜索一个网页中包含特定文本的所有href链接。我已经做了,但是如果文本换行,beauthoulsoup不会“看到”它,也不会返回链接。在

soup = BeautifulSoup(webpageAdress, "lxml")

path = soup.findAll('a', href=True, text="Something3")
print(path)

示例:

像这样,它返回Something3文本的Href:

^{2}$

像这样,它不会返回Something3文本的Href:

...
<a href="page1/somethingC.aspx">
Something3</a>
...

不同的是,Href text(Something3)在新行中。 我不能更改HTML代码,因为我不是那个网页的网站管理员。在

你知道我该怎么解决吗?在

注意:我已经试过使用汤。更换('\n','').replace('\r',''),但我得到错误NoneType'对象不可调用。在


Tags: pathtext文本网页链接requestslxmlhref
3条回答

以及一个没有正则表达式的解决方案:

path = soup.select('a')
if path[0].getText().strip() == 'Something3':
print(path)

输出:

^{pr2}$

您可以将:contains伪类与bs4 4.7.1一起使用

from bs4 import BeautifulSoup as bs

html = '<a href="page1/somethingC.aspx">Something3</a>'
soup = bs(html, 'lxml')
links = [link.text for link in soup.select('a:contains(Something3)')]
print(links)

可以使用regex查找包含“Something3”的任何文本:

html = '''<a href="page1/somethingC.aspx">Something3</a>

<a href="page1/somethingC.aspx">
Something3</a>'''


from bs4 import BeautifulSoup
import re

soup = BeautifulSoup(html, "lxml")

path = soup.findAll('a', href=True, text=re.compile("Something3"))

for link in path:
    print (link['href'])

相关问题 更多 >