两种几乎相同的代码,一种有效,但另一种无效

时间:2020-03-15 10:09:33

标签: python web-scraping beautifulsoup

我不知道为什么第一个代码有效,而第二个代码无效。在“ adidas”代码之后,我得到答案“连接异常终止,OSError 10054”。我在网站上听说过有关API的一些信息,说实话我不知道这是什么,但是我认为那是与:D

相关的

工作原理:

import requests
from bs4 import BeautifulSoup

odpowiedz = requests.get("https://www.nike.com/pl/w?q=react%20270&vst=react%20270")
soup = BeautifulSoup(odpowiedz.text, 'html.parser')

不起作用:

import requests
from bs4 import BeautifulSoup

odpowiedz = requests.get("https://www.adidas.pl/search?q=ultraboost")
soup = BeautifulSoup(odpowiedz.text, 'html.parser')

2 个答案:

答案 0 :(得分:0)

您可以使用selenium代替获取页面源的请求

from selenium import webdriver
from bs4 import BeautifulSoup

driver = webdriver.Chrome()
driver.get("https://www.adidas.pl/search?q=ultraboost")
source = driver.page_source

soup = BeautifulSoup(source, 'html.parser')

如果要在获取页面源代码后退出chrome,请使用driver.quit()

from selenium import webdriver
from bs4 import BeautifulSoup

driver = webdriver.Chrome()
driver.get("https://www.adidas.pl/search?q=ultraboost")
source = driver.page_source
driver.quit()

soup = BeautifulSoup(source, 'html.parser')

如果您不想显示镶边选项卡

from selenium import webdriver
from bs4 import BeautifulSoup

options = webdriver.ChromeOptions()
options.add_argument('--headless')
driver = webdriver.Chrome(options=options)
driver.get("https://www.adidas.pl/search?q=ultraboost")
source = driver.page_source
driver.quit()

soup = BeautifulSoup(source, 'html.parser')

答案 1 :(得分:0)

Daweo 是正确的,阿迪达斯服务器检查User-Agent标头。

这对我有用:

import requests
from bs4 import BeautifulSoup

headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0",
           #"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
           #"Accept-Language": "en-US,en;q=0.5",
           }

odpowiedz = requests.get("https://www.adidas.pl/search?q=ultraboost", headers=headers)
soup = BeautifulSoup(odpowiedz.text, 'html.parser')

它甚至接受"aaaaaaaaaaaaaadaaaMozilla"

对于Adidas.com,如果您没有可接受的User-Agent,则会返回一个说明原因的页面:

在高流量产品发布期间,我们具有额外的安全性,可防止机器人进入我们的网站。我们这样做是为了保护客户并为所有人提供获得运动鞋的公平机会。您设置中的某些内容一定已经触发了我们的安全系统,因此我们不能允许您进入该网站。

相关问题