首页 > 解决方案 > 从特定网站抓取已停止工作

问题描述

所以几周前我写了这个程序,它成功地在一些在线商店上抓取了一些信息,但现在它已经停止工作而没有我更改代码?

这可能是网站本身已更改的内容,还是我的代码有问题?

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

标签: pythonweb-scrapingbeautifulsoup

解决方案


解决方案有点多步骤。

  1. 尝试在 Firefox 中调用一次要抓取的页面
  2. 使用 browser_cookie3 库提取 cookie
  3. 确保它们没有过期
  4. 使用 requests.get(url, cookies=browser_cookie3.firefox()) 中的 cookie
  5. 使用如下标题

希望它有效!快乐刮

我自己试过了,效果很好!!

 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',
}

推荐阅读