首页 > 解决方案 > 从 href python '#' 中删除元素

问题描述

我希望从以下代码中删除 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)

标签: pythonhref

解决方案


您可以使用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不是一个函数(并且程序的这个分支无论如何都无法访问)。


推荐阅读