9 html python beautifulsoup web-scraping
我有以下内容:
html =
'''<div class=“file-one”>
<a href=“/file-one/additional” class=“file-link">
<h3 class=“file-name”>File One</h3>
</a>
<div class=“location”>
Down
</div>
</div>'''
Run Code Online (Sandbox Code Playgroud)
并希望得到的文本href是/file-one/additional.所以我做了:
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')
link_text = “”
for a in soup.find_all(‘a’, href=True, text=True):
link_text = a[‘href’]
print “Link: “ + link_text
Run Code Online (Sandbox Code Playgroud)
但它只是打印一个空白,没有.只是Link:.所以我在另一个网站上测试了它,但是使用了不同的HTML,并且它有效.
我能做错什么?或者是否有可能该网站故意编程不返回href?
提前谢谢,一定会upvote /接受答复!
t.m*_*dam 16
html中的'a'标记没有直接的文字,但包含一个带有一些文字的'h3'标签.这意味着text是.find_all(),所以text不会选择任何标记.
如果仅使用href和lambda参数选择标记,然后在循环中添加条件以检查标记中是否有任何文本,则可以解决此问题.
soup = BeautifulSoup(html, 'html.parser')
links_with_text = []
for a in soup.find_all('a', href=True):
if a.text:
links_with_text.append(a['href'])
Run Code Online (Sandbox Code Playgroud)
或者你可以使用列表理解,如果你更喜欢单行.
links_with_text = [a['href'] for a in soup.find_all('a', href=True) if a.text]
Run Code Online (Sandbox Code Playgroud)
或者你可以通过一个.find_all()在href.
tags = soup.find_all(lambda tag: tag.name == 'a' and tag.get('href') and tag.text)
Run Code Online (Sandbox Code Playgroud)
小智 6
您还可以使用 attrs 通过正则表达式搜索获取 href 标签
soup.find('a', href = re.compile(r'[/]([a-z]|[A-Z])\w+')).attrs['href']
Run Code Online (Sandbox Code Playgroud)