【发布时间】: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 开头的?