我有以下几点:
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>'''只想得到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但它只是打印一个空白,什么都不打印。只有Link:。所以我在另一个网站上用不同的HTML测试了它,它工作了。
我能做错什么呢?或者,是否存在该站点故意编程为不返回href的可能性?
提前感谢你,我一定会给你上票/接受回复!
发布于 2017-05-06 08:42:36
html中的'a‘标签不直接包含任何文本,但它包含一个包含文本的'h3’标签。这意味着text为None,并且.find_all()无法选择标记。通常,如果标记包含除文本内容之外的任何其他html元素,则不要使用text参数。
如果仅使用标记的名称(和href关键字参数)来选择元素,则可以解决此问题。然后在循环中添加一个条件,以检查它们是否包含文本。
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'])或者,如果您更喜欢一行程序,也可以使用列表理解。
links_with_text = [a['href'] for a in soup.find_all('a', href=True) if a.text]或者,您可以向.find_all()传递一个lambda。
tags = soup.find_all(lambda tag: tag.name == 'a' and tag.get('href') and tag.text)如果你想收集所有的链接,不管它们有没有文本,只要选择所有有'href‘属性的'a’标签即可。锚标记通常有链接,但这不是必需的,所以我认为最好使用href参数。
使用.find_all()。
links = [a['href'] for a in soup.find_all('a', href=True)]在CSS选择器中使用.select()。
links = [a['href'] for a in soup.select('a[href]')]发布于 2018-06-04 19:53:00
您还可以使用attrs通过regex搜索来获取href标记
soup.find('a', href = re.compile(r'[/]([a-z]|[A-Z])\w+')).attrs['href']发布于 2017-05-06 07:18:33
首先,使用不使用curly quotes.
soup.find_all中删除
https://stackoverflow.com/questions/43814754
复制相似问题