python - 从 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)
解决方案
您可以使用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
不是一个函数(并且程序的这个分支无论如何都无法访问)。
推荐阅读
- iphone - iOS12 中的 EKCalendar 标题为空白
- python - Pandas - 将多个分类列转换为同一组列
- cuda - 在 CUDA 中每个网格(x 维度)启动超过 65536 个块
- git - GitHub 字体对齐问题:源代码查看器中的多余空格
- sql - 如何为 ColdFusion FindNoCase If 条件编写 SQL 查询?
- c# - PDFsharp PdfDocument.Save 导致任何其他保存时出现空白页
- octobercms - 如何更改十月 CMS 中后端列表行的背景颜色?
- c# - GetDrawable 已过时
- r - 在 dplyr 的过滤命令中使用 contains() 时出错
- c# - CancellationTokenSource.Cancel() 挂起