我正在使用美汤,请求打印本网站文章全文
https://www.vanityfair.com/style/society/2014/06/monica-lewinsky-humiliation-culture
这是我的代码:
import requests
from bs4 import BeautifulSoup
url = requests.get("https://www.vanityfair.com/style/society/2014/06/monica-lewinsky-humiliation-culture")
html = url.text
page = BeautifulSoup(html, 'html.parser')
match = page.find_all('div', 'parbase cn_text')
page_list = [[k.get_text() for k in i.find_all('p')] for i in match]
for i in page_list[:-2]:
for k in i:
print(k + '\n')
我的代码运行没有任何错误,但在输出中没有显示任何文本,请帮我找到我的错误
答案 0 :(得分:0)
要获取文章数据,请选择具有 div
类的 article__chunks
。属于它的文章数据。
import requests
from bs4 import BeautifulSoup
url = requests.get("https://www.vanityfair.com/style/society/2014/06/monica-lewinsky-humiliation-culture")
html = url.text
page = BeautifulSoup(html, 'html.parser')
match = page.find('div', {'class': 'article__chunks'})
page_list = [[k.get_text() for k in i.find_all('p')] for i in match]
for i in page_list[:-2]:
for k in i:
print(k + '\n')
答案 1 :(得分:0)
您尝试使用两个不存在的类来 find_all()
div 标签,因此 match
为空。
使用正确的模式,我使用了 css 选择器来避免额外的循环:
select('article.article.main-content p')
列表推导式如下所示:
[p.get_text() for p in page.select('article.article.main-content p')]
工作示例
import requests
from bs4 import BeautifulSoup
url = requests.get("https://www.vanityfair.com/style/society/2014/06/monica-lewinsky-humiliation-culture")
html = url.text
page = BeautifulSoup(html, 'html.parser')
print(*[p.get_text() for p in page.select('article.article.main-content p')], sep='\n')