Python + BeautifulSoup:如何获取“a"元素的“href"属性? [英] Python + BeautifulSoup: How to get ‘href’ attribute of ‘a’ element?

查看:55
本文介绍了Python + BeautifulSoup:如何获取“a"元素的“href"属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下几点:

 html ='''

<a href="/file-one/additional" class="file-link"><h3 class="file-name">文件一</h3></a><div class="location">向下

</div>'''

并且只想获取 href 的文本,即 /file-one/additional.所以我做到了:

from bs4 import BeautifulSoup汤 = BeautifulSoup(html, 'html.parser')链接文本="对于一个汤.find_all('a', href=True, text=True):link_text = a[‘href’]打印链接:"+ link_text

但它只是打印一个空白,什么都没有.只是链接:.所以我在另一个网站上测试了它,但使用了不同的 HTML,它奏效了.

我可能做错了什么?或者该站点是否有可能故意编程为不返回 href?

预先感谢您,并一定会赞成/接受答案!

解决方案

html 中的 'a' 标签不直接包含任何文本,但它包含一个带有文本的 'h3' 标签.这意味着 text 为 None,并且 .find_all() 无法选择标签.如果标签包含除文本内容之外的任何其他 html 元素,通常不要使用 text 参数.

如果您仅使用标签名称(和 href 关键字参数)来选择元素,则可以解决此问题.然后在循环中添加一个条件以检查它们是否包含文本.

soup = BeautifulSoup(html, 'html.parser')links_with_text = []对于一个汤.find_all('a', href=True):如果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]

或者你可以传递一个 lambda.find_all().

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)]

.select() 与 CSS 选择器一起使用.

links = [a['href'] for a in soup.select('a[href]')]

I have the following:

  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>'''

And would like to get just the text of href which is /file-one/additional. So I did:

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

But it just prints a blank, nothing. Just Link:. So I tested it out on another site but with a different HTML, and it worked.

What could I be doing wrong? Or is there a possibility that the site intentionally programmed to not return the href?

Thank you in advance and will be sure to upvote/accept answer!

解决方案

The 'a' tag in your html does not have any text directly, but it contains a 'h3' tag that has text. This means that text is None, and .find_all() fails to select the tag. Generally do not use the text parameter if a tag contains any other html elements except text content.

You can resolve this issue if you use only the tag's name (and the href keyword argument) to select elements. Then add a condition in the loop to check if they contain text.

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'])

Or you could use a list comprehension, if you prefer one-liners.

links_with_text = [a['href'] for a in soup.find_all('a', href=True) if a.text]

Or you could pass a lambda to .find_all().

tags = soup.find_all(lambda tag: tag.name == 'a' and tag.get('href') and tag.text)


If you want to collect all links whether they have text or not, just select all 'a' tags that have a 'href' attribute. Anchor tags usually have links but that's not a requirement, so I think it's best to use the href argument.

Using .find_all().

links = [a['href'] for a in soup.find_all('a', href=True)]

Using .select() with CSS selectors.

links = [a['href'] for a in soup.select('a[href]')]

这篇关于Python + BeautifulSoup:如何获取“a"元素的“href"属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆