python - 阅读美丽汤的链接列表
问题描述
我一直在尝试从我成功提取的 URL 列表中读取链接。我的问题是TypeError Traceback (most recent call last)
当我尝试阅读整个列表时得到一个。但是,当我阅读单个链接时,该urlopen(urls).read()
行的执行没有问题。
response = requests.get('some_website')
doc = BeautifulSoup(response.text, 'html.parser')
headlines = doc.find_all('h3')
links = doc.find_all('a', { 'rel':'bookmark' })
for link in links:
print(link['href'])
for urls in links:
raw_html = urlopen(urls).read() <----- this row here
articles = BeautifulSoup(raw_html, "html.parser")
解决方案
考虑使用BeautifulSoup
with requests.Session()
,以提高重用连接的效率,并添加标头
import requests
from bs4 import BeautifulSoup
with requests.Session() as s:
url = 'https://newspunch.com/category/news/us/'
headers = {'User-Agent': 'Mozilla/5'}
r = s.get(url, headers = headers)
soup = BeautifulSoup(r.text, 'lxml')
links = [item['href'] for item in soup.select('[rel=bookmark]')]
for link in links:
r = s.get(link)
soup = BeautifulSoup(r.text, 'lxml')
print(soup.select_one('.entry-title').text)
推荐阅读
- c++ - 我想改变条件,但我不能
- sql - 如何从两个不同的表中计算和和减法
- django - django.extra() 中是否有左连接,它可以帮助我在 django 中加入没有任何关系的表
- bash - 如何从 lcov --summary 命令中仅读取行覆盖率并存储在某些 shell 脚本变量中?
- typescript - 如何为 Visual Studio 代码添加方法描述?
- python - 将有序字典转换为 pandas 列
- android - 怯场——利用?- 对相同文件的重复请求
- dvc - 数据版本控制 (DVC) 就地编辑文件导致循环依赖
- python - 如何通过索引位置在 df 上插入后行?
- angularjs - 如何在 AngularJS 表单中嵌套 Angular 2+ 表单?