加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-17 17:41:49 所属栏目:Python 来源:网络整理
导读:我正在尝试使用Selenium或Beautifulsoup 4从https://www.finishline.com抓取数据.到目前为止,我一直没有成功,所以我向Stackoverflow寻求帮助-希望有人知道绕过其抓取保护的方法. 我尝试使用Beautifulsoup 4和Selenium.以下是一些简单的示例. 我的主程序中使

我正在尝试使用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

Beautifulsoup 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)

硒代码:

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()

这两个片段都是尝试从产品页面获取产品标题的尝试.

Beautifulsoup 4片段有时会卡住而无所事事,而有时返回

requests.exceptions.ConnectionError: ('Connection aborted.',OSError("(10060,'WSAETIMEDOUT')"))

硒片段返回

<selenium.webdriver.remote.webelement.WebElement (session="b3707fb7d7b201e2fa30dabbedec32c5",element="0.10646785765405364-1")>

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

x = driver.find_element_by_xpath("//h1[1]")

x = driver.find_element_by_xpath("//h1[1]").text

它会返回“访问被拒绝”,这也是网站本身有时在浏览器中返回的内容.清除cookie可以绕过它.

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

最佳答案
服务器由于用户代理而拒绝了该请求,因此我向请求添加了用户代理.

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,attrs={'id': 'title'}).text.strip()
print(x)

输出:

Men's Nike Air Max 95 SE Casual Shoes

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读