python - 从特定网站抓取已停止工作
问题描述
所以几周前我写了这个程序,它成功地在一些在线商店上抓取了一些信息,但现在它已经停止工作而没有我更改代码?
这可能是网站本身已更改的内容,还是我的代码有问题?
import requests
from bs4 import BeautifulSoup
url = 'https://www.continente.pt/stores/continente/pt-pt/public/Pages/ProductDetail.aspx?ProductId=7104665(eCsf_RetekProductCatalog_MegastoreContinenteOnline_Continente)'
res = requests.get(url)
html_page = res.content
soup = BeautifulSoup(html_page, 'html.parser')
priceInfo = soup.find('div', class_='pricePerUnit').text
priceInfo = priceInfo.replace('\n', '').replace('\r', '').replace(' ', '')
productName = soup.find('div', class_='productTitle').text.replace('\n', ' ')
productInfo = (soup.find('div', class_='productSubtitle').text
+ ', ' + soup.find('div', class_='productSubsubtitle').text)
print('Nome do produto: ' + productName)
print('Detalhes: ' + productInfo)
print('Custo: ' + priceInfo)
我知道我正在搜索的内容确实存在并且 url 仍然有效,那么可能是什么问题?我将 priceInfo 分成 2 行,因为第一个声明中存在错误,因为它返回没有文本属性的 NoneType
解决方案
解决方案有点多步骤。
- 尝试在 Firefox 中调用一次要抓取的页面
- 使用 browser_cookie3 库提取 cookie
- 确保它们没有过期
- 使用 requests.get(url, cookies=browser_cookie3.firefox()) 中的 cookie
- 使用如下标题
希望它有效!快乐刮
我自己试过了,效果很好!!
headers = {
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'Sec-Fetch-Site': 'none',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-User': '?1',
'Sec-Fetch-Dest': 'document',
'Accept-Language': 'en-US,en;q=0.9,de;q=0.8',
}
推荐阅读
- javascript - 如何从不同的端口访问组件
- node.js - 各种 axios 调用相对于前一个
- python - django中get_form_kwargs方法的用法需要清楚的解释
- c++ - 如何在函数中初始化数组,其长度由 C++ 中的形式参数给出
- sql - 具有两个“HAVING”条件的 Oracle 查询
- javascript - Height 100vh - JavaScript 中其他元素的高度
- ruby - 如何从带有给定子字符串的 a 开头的单词的开头到结尾获取子字符串 - Ruby
- php - 使用高级自定义字段日期选择器时出现致命错误
- listview - Listview不能在tabview中滚动?(扑)
- unity3d - 我应该使用什么统一工具在屏幕上绘制 2d 精灵?