【发布时间】:2022-10-22 15:25:22
【问题描述】:
我想用 python/BeautifulSoup 抓取一个网站,包括这篇文章:
https://www.electrive.com/2022/02/20/byd-planning-model-3-like-800-volt-sedan-called-seal/
在每篇文章的末尾,您总能找到来源。在上面的链接的情况下,这是:
在本网站上的某些文章中,只给出了一个来源,但有时会给出两个或三个不同的来源。所以代码需要考虑这一点。
理想情况下,我想要以下输出格式:“文本(href)”
xchuxing.com (https://xchuxing.com/article/45850)
cnevpost.com (https://cnevpost.com/2022/02/18/byd-seal-set-to-become-new-tesla-model-3-challenger/)
这是我的第一个代码:
from bs4 import BeautifulSoup
import requests
import csv
URL = 'https://www.electrive.com/2022/02/20/byd-planning-model-3-like-800-volt-sedan-called-seal/'
(response := requests.get(URL)).raise_for_status()
soup = BeautifulSoup(response.text, 'lxml')
article = soup.find()
source = [c for c in article.find('section', class_='content').find_all('a')]
for link in source[3:]:
link.get('href')
print (link)
截至目前的输出:
<a href="https://cnevpost.com/2022/02/18/byd-seal-set-to-become-new-tesla-model-3-challenger/" rel="noopener" target="_blank">cnevpost.com</a>
[Finished in 345ms]
【问题讨论】:
-
link.get('href')line Effective 什么都不做 - 你检索 href 并把它扔掉。将其存储/绑定到名称或打印。您遍历所有链接(标签)并打印最后一个,而不是 href
标签: python html web-scraping beautifulsoup