使用 BS4 或 Selenium 从 finishline.com 进行网页抓取

kam*_*111 5 python selenium beautifulsoup web-scraping

我正在尝试使用 Selenium 或 Beautifulsoup 4 从https://www.finishline.com抓取数据。到目前为止,我还没有成功,所以我向 Stackoverflow 寻求帮助 - 希望有人知道绕过抓取保护的方法。

我尝试使用 Beautifulsoup 4 和 Selenium。下面是一些简单的例子。

我的主程序中使用的常规导入:

import requests
import csv
import io
import os
import re
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from datetime import datetime
from bs4 import BeautifulSoup
Run Code Online (Sandbox Code Playgroud)

美丽汤4代码:

data2 = requests.get("https://www.finishline.com/store/product/mens-nike-air-max-95-se-casual-shoes/prod2783292?styleId=AJ2018&colorId=004")
soup2 = BeautifulSoup(data2.text, 'html.parser')

x = soup2.find('h1', attrs={'id': 'title'}).text.strip()
print(x)
Run Code Online (Sandbox Code Playgroud)

硒代码:

options = Options()
options.headless = True
options.add_argument('log-level=3')
driver = webdriver.Chrome(options=options)
driver.get("https://www.finishline.com/store/product/mens-nike-air-max-95-se-casual-shoes/prod2783292?styleId=AJ2018&colorId=004") 
x = driver.find_element_by_xpath("//h1[1]")
print(x)
driver.close()
Run Code Online (Sandbox Code Playgroud)

这两个片段都试图从产品页面获取产品标题。

Beautifulsoup 4 片段有时会卡住并且什么都不做,有时又会返回

requests.exceptions.ConnectionError: ('Connection aborted.', OSError("(10060, 'WSAETIMEDOUT')"))
Run Code Online (Sandbox Code Playgroud)

Selenium 片段返回

<selenium.webdriver.remote.webelement.WebElement (session="b3707fb7d7b201e2fa30dabbedec32c5", element="0.10646785765405364-1")>
Run Code Online (Sandbox Code Playgroud)

这意味着它确实找到了该元素,但是当我尝试通过更改将其转换为文本时

x = driver.find_element_by_xpath("//h1[1]")
Run Code Online (Sandbox Code Playgroud)

x = driver.find_element_by_xpath("//h1[1]").text
Run Code Online (Sandbox Code Playgroud)

它返回Access Denied,这也是网站本身有时在浏览器中返回的内容。可以通过清除cookie来绕过它。

有谁知道从该网站抓取数据的方法吗?提前致谢。

Soh*_*Das 3

由于用户代理的原因,请求被服务器拒绝,我将用户代理添加到请求中。

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'
}
data2 = requests.get("https://www.finishline.com/store/product/mens-nike-air-max-95-se-casual-shoes/prod2783292?styleId=AJ2018&colorId=004",headers=headers)
soup2 = BeautifulSoup(data2.text, 'html.parser')

x = soup2.find('h1', attrs={'id': 'title'}).text.strip()
print(x)
Run Code Online (Sandbox Code Playgroud)

输出:

Men's Nike Air Max 95 SE Casual Shoes
Run Code Online (Sandbox Code Playgroud)