【问题标题】:removing elements from href python '#'从 href python '#' 中删除元素
【发布时间】:2020-03-19 14:57:21
【问题描述】:

我希望从以下代码中删除 href 元素,我可以在运行时返回结果,但它不会从 python 中的 url 列表中删除“#”和“#contents”。

from bs4 import BeautifulSoup
import requests

url = 'https://www.census.gov/programs-surveys/popest.html'
response = requests.get(url)
data = response.text
soup = BeautifulSoup(data, 'html.parser')
links_with_text = []

for a in soup.find_all('a', href=True): 
      if a.text: 
          links_with_text.append(a['href'])
      elif a.text:
          links_with_text.decompose(a['#content','#'])

print(links_with_text)

【问题讨论】:

  • 欢迎来到 SO! list.decompose 不是一个函数,这是一件好事,因为elif a.text 无法访问(与if a.text 的情况相同)。您可以使用if a.text and not a['href'].startswith("#"): 跳过主题标签链接,但除此之外您还想完成什么?请发布预期的输出。谢谢!
  • 您好,感谢您的反馈!我希望返回一个 url 列表并删除诸如“#contents”之类的元素,以便该列表仅返回 url。最终输出应该是 url 的列表。
  • 好的——我注意到有一个"/"。你也想删除它吗?
  • 是的,“/”也需要删除。
  • 是否有您真正追求的特定网址?页面上的部分或其他内容?可能有更有效的方法来做到这一点,或者你只想要那些以 http/https 开头的?

标签: python href


【解决方案1】:

您可以使用string#startswith 将任何以"#" 开头的链接列入黑名单,或将任何以"http""https" 开头的链接列入白名单。由于您的数据中有像"/" 这样的href,我会使用第二个选项。

import requests
from bs4 import BeautifulSoup

url = 'https://www.census.gov/programs-surveys/popest.html'
soup = BeautifulSoup(requests.get(url).text, 'html.parser')
links_with_text = []

for a in soup.find_all('a', href=True): 
      if a.text and a['href'].startswith('http'):
          links_with_text.append(a['href'])

print(links_with_text)

请注意,list.decompose 不是函数(而且程序的这个分支无论如何都无法访问)。

【讨论】:

  • 感谢 ggorlen 的帮助!
【解决方案2】:

如果您只想要 https/http 链接,请通过 href 属性选择器使用内置的 css 过滤,并以运算符开头。如果安装了“lxml”,它也是一个更快的解析器。

import requests
from bs4 import BeautifulSoup

url = 'https://www.census.gov/programs-surveys/popest.html'
soup = BeautifulSoup(requests.get(url).text, 'lxml')
links = [i['href'] for i in soup.select('[href^=http]')]

【讨论】:

  • 感谢 QHarr 的帮助!
  • 不客气。如果您需要更具体的子集,请告诉我们。
  • 史蒂文,一旦您对问题的解决感到满意,您应该接受对您问题的回答。你 get a badge 这样做,this link 可能会有所帮助。谢谢你的好问题!
猜你喜欢
  • 2012-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-13
  • 1970-01-01
  • 1970-01-01
  • 2015-02-11
相关资源
最近更新 更多