gpt4 book ai didi

python - 无法从网页中抓取产品标题

转载 作者:行者123 更新时间:2023-12-04 04:30:20 26 4
gpt4 key购买 nike

我试图在此 webpage 中抓取可用产品的标题使用请求模块,但脚本总是抛出 AttributeError即使产品标题在页面源中( ctrl + U )。
我试过( throws AttributeError ):

import requests
from bs4 import BeautifulSoup

link = 'https://www.cclonline.com/product/334427/GV-N3070AORUS-M-8GD-1-1/Graphics-Cards/Gigabyte-AORUS-GeForce-RTX-3070-MASTER-8GB-Overclocked-Graphics-Card-rev-1-1-/VGA5934/'

headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36',
}

res = requests.get(link, headers=headers)
soup = BeautifulSoup(res.text,"lxml")
try:
product_title = soup.select_one("h1 > span").get_text(strip=True)
except AttributeError: product_title = ""
print(product_title)
预期输出:
Gigabyte GeForce RTX 3070 Aorus Master 8GB OC GPU

How can I scrape the product title from that webpage?


PS我试过这个库 cloudscraper同样,但没有运气。
编辑:
这就是我得到的 raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 403 Client Error: Forbidden for url当我运行以下代码时:
import cfscrape

url = 'https://www.cclonline.com/product/334427/GV-N3070AORUS-M-8GD-1-1/Graphics-Cards/Gigabyte-AORUS-GeForce-RTX-3070-MASTER-8GB-Overclocked-Graphics-Card-rev-1-1-/VGA5934/'

headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36',
}

token, agent = cfscrape.get_tokens(url, headers=headers)
print(token, agent)
我知道我可以使用 cf_clearance 的值在 cookie 中访问页面内容,如果我可以从上面的尝试中获得 token 的值。

最佳答案

这只是研究的一个占位符,可能对其他查看 Cloudflare 绕过问题的人有用。
用例

从使用 Cloudflare CAPTCHA or Javascript challenge 的网站抓取信息以加强保护。
Python请求

使用标准 Python 请求。获取 Cloudflare 服务将返回 403 Forbidden 错误代码。

import requests

URL = 'https://www.cclonline.com/product/334427/GV-N3070AORUS-M-8GD-1-1/Graphics-Cards/Gigabyte-AORUS-GeForce-RTX' \
'-3070-MASTER-8GB-Overclocked-Graphics-Card-rev-1-1-/VGA5934/'

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36'}

response = requests.get(URL, headers=headers)
print(f'Status Code: {response.status_code}')
print(f'Status Code Reason: {response.reason}')
# output
Status Code: 403
Status Code Reason: Forbidden
如果我们查看 response.headers,我们可以看到 Cloudflare 服务器正在将我们的请求代理到目标 URL。
...continued from the code above
for key, value in response.headers.items():
print(f'KEY NAME: {key}')
print(f'KEY VALUE: {value}')
print('-----------------------')
# output
KEY NAME: Date
KEY VALUE: Sun, 13 Jun 2021 16:39:03 GMT
-----------------------
KEY NAME: Content-Type
KEY VALUE: text/html; charset=UTF-8
-----------------------
KEY NAME: Transfer-Encoding
KEY VALUE: chunked
-----------------------
KEY NAME: Connection
KEY VALUE: close
-----------------------
KEY NAME: Permissions-Policy
KEY VALUE: accelerometer=(),autoplay=(),camera=(),clipboard-read=(),clipboard-write=(),fullscreen=(),geolocation=(),gyroscope=(),hid=(),interest-cohort=(),magnetometer=(),microphone=(),payment=(),publickey-credentials-get=(),screen-wake-lock=(),serial=(),sync-xhr=(),usb=()
-----------------------
KEY NAME: Cache-Control
KEY VALUE: private, max-age=0, no-store, no-cache, must-revalidate, post-check=0, pre-check=0
-----------------------
KEY NAME: Expires
KEY VALUE: Thu, 01 Jan 1970 00:00:01 GMT
-----------------------
KEY NAME: X-Frame-Options
KEY VALUE: SAMEORIGIN
-----------------------
KEY NAME: cf-request-id
KEY VALUE: 0aa7d6c7c4000007ff7201b000000001
-----------------------
KEY NAME: Expect-CT
KEY VALUE: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
-----------------------
KEY NAME: Set-Cookie
KEY VALUE: __cf_bm=72427e2af66c7177feeb88a847fae9c26b66c681-1623602343-1800-AZAmqDfaHZU8IXOH/i3BBVf8pGcws0Gc1Tln5yKUepe3utWlCpagxvALDW6wiHd2pli9Zl45Mg8gC/QSoUFhoes=; path=/; expires=Sun, 13-Jun-21 17:09:03 GMT; domain=.cclonline.com; HttpOnly; Secure; SameSite=None
-----------------------
KEY NAME: Vary
KEY VALUE: Accept-Encoding
-----------------------
KEY NAME: Server
KEY VALUE: cloudflare
-----------------------
KEY NAME: CF-RAY
KEY VALUE: 65ecc0b9383b07ff-ATL
-----------------------
KEY NAME: Content-Encoding
KEY VALUE: gzip
-----------------------

如果我们查看与 Python 请求关联的 response.text,我们可以看到与 Cloudflare 保护相关的其他证据。
...continued from the code above
print(response.text)
# output

truncated...

<title>Please Wait... | Cloudflare</title>
<meta name="captcha-bypass" id="captcha-bypass" />

truncated...

<form class="challenge-form managed-form" id="challenge-form" action="/product/334427/GV-N3070AORUS-M-8GD-1-1/Graphics-Cards/Gigabyte-AORUS-GeForce-RTX-3070-MASTER-8GB-Overclocked-Graphics-Card-rev-1-1-/VGA5934/?__cf_chl_managed_tk__=7d4597196bb14948881846ca16631b64c55f06d3-1623602854-0-AcX2yHJM2sCalL03Opq9RiFjASeYE0Xs0KG4XeG1lezzhzEyu-bL8xsdHuEjNIIKaJkWEmha4DhViRlqWEP_HREOdA8YAY7nnNkBAHbNMs6p_AWgYNLPnSNM13PO2I96hdABtoaaKjOzV4AyJQJ8f08XEW2flN97rPxIMeiR0tI1a3PiON2dN9E_YCyneAuCUfaYWUNGL0Bqd_rkYp3Ljb2zk_kGWizckr1fvhodSEjEB-ByYVK8ODNox2oZ4XPcmCYJ6UNDmbNc406BjMeTf3e72Z7vgdnt3V714VrGN4w_Y4VQ2X1V0OVKUKEH9B5Rxa_4fEZiMAAdxZ6idg69JYMKftuuLemr53n5WAwTwyX2G7N9jmjtarxEQcCqoj9oY7oSFwQTb3ZVb9i5EeavKaE1_67wxpyPybNidBDxhLazDEMefPZGDsV9mSziuIQ90nS5vn-7sUvC8BJATNWPbh6OduchXy-QcMeYhurtukUCm3oDQMP7r4g4qvDCWI3_-ku7u-B4G2XI2kwM_tLVEZiH5uHPjWpHE6eFWohiCTxd4p7vHg7z5ug9feRalYqu3GfInd82GZ-j-7nCqLDmPh2Sjlu6sJGfopqM3XlBrd1kgRZU3Z4uw6JIIqfH0M6K3_weTtem0-Z1zhDUBbVDvgJVeHNNh_bTxHGWbFB0f80tALBMbt67RftO5u1XBUZ-TRftteXBwJ8gmYzOZTo4lQOGQ_771urYXsTuW_sp8PwxvQpEyCnY8zD8dmVz0-waZhOet8MQMwduN2nfGUOrCMwUYO9McsBqzfsT5PJZVkDm-rYBBwqw0PIwvm1-N8ymAjrpSN6ps4FerqK1uQOo77FLiOq8JCOVqdETIZ9NO07A" method="POST" enctype="application/x-www-form-urlencoded">

truncated...

<input type="hidden" name="r" value="d5db3eb87c9b42ec7f076916611c296abfd2c842-1623602854-0-AXz7+uyFGbpY1aOLgfZMm0oIiiepEo5I5QmdTnvMmL9fDUc4OMEa2CNYXsbHVjOzdYO+PqegjpNL8R3D9LhDc+Xo0y0ira1zO7foozPj0qdcUpNNr2ZOHqgUyKws6dVgeBNUdF+v9+eNFxSHxOhc4DWDLIw9guBqJg1GaBjG3QCQdZmyFbPxXUQtXTFmtVVuqch9qBFLa/u9deMBCxCWi5fyKoOINtyBtyT4p79ITb9T+6T7fl2epMXNHO6xBW2dPnDP1FmjUQ04CG3ydOaDS5qoSFMPr4InVbMcI2NbQYJYPfWjmncMaga6K+NMNvv8wtiyXpEeWsUgFFeQoDJEuvLI+wkI8mT+vXAnXd8LWy9TpEDVK6uxtLF2C75aU7qJxI9RKANGluWYUXeqE1tXgppgZraIGfRWNPVsQZzqd6SK+Zsg8x8UH7oRRD9blMMPMaekcFQ3zT8QQ5BzEc8wEQ68OhmKbFuAeV/YhhWshpm808gcVHIFH17I+0MEidfV/ny5wBSRZJyQUfOSU9iAv/minNWF6ZA21E/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DUneGjBEGnWyiv49DtiG2TLmmIpP1UITmO677eDSoNLHpxp1guMjwL5m3XHKOFNtpLzuiVH4UJdgTjtnmbGHmKGtyy0k3GPZrwyVkZRyS+FZZ5WhTs05rhS+1sg3oDCyTbWeYX9T4VVswRjxq1HsyH8NdZTN4f9BTn9VU0+9JnVAkgLM4JCkV6wqwQf+QMK/MaYWvBwSjYgFUxdEdT7Rls85/M+4GxcaGsiNmsA5Q==">
<input type="hidden" name="cf_captcha_kind" value="h">
<input type="hidden" name="vc" value="4845a44c225a1fa6a61708e11b613971">

truncated...

<script type="text/javascript">
//<![CDATA[
(function(){
var isIE = /(MSIE|Trident\/|Edge\/)/i.test(window.navigator.userAgent);
var trkjs = isIE ? new Image() : document.createElement('img');
trkjs.setAttribute("src", "/cdn-cgi/images/trace/managed/js/transparent.gif?ray=65eccd326d61f331");
trkjs.id = "trk_managed_js";
trkjs.setAttribute("alt", "");
document.body.appendChild(trkjs);
var cpo=document.createElement('script');
cpo.type='text/javascript';
cpo.src="/cdn-cgi/challenge-platform/h/g/orchestrate/managed/v1?ray=65eccd326d61f331";
document.getElementsByTagName('head')[0].appendChild(cpo);
}());
//]]>
</script>

上述信息显示,传输到目标 URL 的 Python 请求被 Cloudflare 服务器拦截,这对请求进行了挑战。在允许继续初始请求之前,必须绕过此质询。
cfscrape 包

OP 表示他们试图使用 cfscrape从 Cloudflare 服务器获取 token 信息的 Python 包。
标准 cfscrape 请求提供与 Python 请求相同的响应。
import cfscrape

URL = 'https://www.cclonline.com/product/334427/GV-N3070AORUS-M-8GD-1-1/Graphics-Cards/Gigabyte-AORUS-GeForce-RTX' \
'-3070-MASTER-8GB-Overclocked-Graphics-Card-rev-1-1-/VGA5934/'

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36'}

scraper = cfscrape.create_scraper(delay=10)
response = scraper.get(URL, headers=headers)
print(f'Status Code: {response.status_code}')
print(f'Status Code Reason: {response.reason}')
# output
Status Code: 403
Status Code Reason: Forbidden

cfscrape 包还支持函数 get_tokens 和 get_cookie_string,但是这两个函数都会产生 403 Forbidden 错误代码。
来自 cfscrape 源代码:
def is_cloudflare_captcha_challenge(resp):
return (
resp.status_code == 403
and resp.headers.get("Server", "").startswith("cloudflare")
and b"/cdn-cgi/l/chk_captcha" in resp.content
)


# the function above is called from this

def request(self, method, url, *args, **kwargs):
resp = super(CloudflareScraper, self).request(method, url, *args, **kwargs)

# Check if Cloudflare captcha challenge is presented
if self.is_cloudflare_captcha_challenge(resp):
self.handle_captcha_challenge(resp, url)

# Check if Cloudflare anti-bot "I'm Under Attack Mode" is enabled
if self.is_cloudflare_iuam_challenge(resp):
resp = self.solve_cf_challenge(resp, **kwargs)

return resp

handle_captcha_challenge 函数试图解决 Cloudflare javascript 挑战。 This section of the code是什么失败了。目前尚不清楚该部分的哪一部分失败,因此需要进行额外的研究和测试。
请注意:根据软件包的开发人员 the module is no longer supported .
云层包

OP 还表示他们试图使用 cloudscraper从 Cloudflare 服务器获取 token 信息的 Python 包。 cloudcraper是从cfscrape fork 出来的,没什么值(value),所以语法类似。
cloudcraper 获得与 cfscrape 相同的 403 Forbidden 错误代码。
import cloudscraper

URL = 'https://www.cclonline.com/product/334427/GV-N3070AORUS-M-8GD-1-1/Graphics-Cards/Gigabyte-AORUS-GeForce-RTX' \
'-3070-MASTER-8GB-Overclocked-Graphics-Card-rev-1-1-/VGA5934/'

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36'}

scraper = cloudscraper.create_scraper()
response = scraper.get(URL)
print(f'Status Code: {response.status_code}')
print(f'Status Code Reason: {response.reason}')
# output
Status Code: 403
Status Code Reason: Forbidden
cloudcraper 包还支持函数 get_tokens 和 get_cookie_string,但是这两个函数都会产生 403 Forbidden 错误代码。
Selenium 包

OP 还表示他们试图使用 selenium python 包。
特别说明:在我的测试过程中,我将 selenium 与 Google Chrome、Mozilla Firefox 和 Microsoft Edge 的 webdrivers 一起使用。
在过去 12 个月内,这些选项可用于 selenium 以绕过 Cloudflare 保护。不幸的是,这些选项今天不起作用
chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
chrome_options.add_experimental_option('useAutomationExtension', False)
# additional disable-blink-features are available in Chromium source code on Github
chrome_options.add_argument("--disable-blink-features=AutomationControlled")
下面是使用 Chrome webdriver 和上述开关的 selenium 代码示例。
from selenium import webdriver

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument(
"user-agent=Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36")
chrome_options.add_argument("start-maximized")
chrome_options.add_argument("--disable-blink-features=AutomationControlled")
chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
chrome_options.add_experimental_option('useAutomationExtension', False)

driver = webdriver.Chrome(executable_path='/usr/local/bin/chromedriver', options=chrome_options)
URL = "https://www.cclonline.com/product/334427/GV-N3070AORUS-M-8GD-1-1/Graphics-Cards/Gigabyte-AORUS-GeForce-RTX-3070-MASTER-8GB-Overclocked-Graphics-Card-rev-1-1-/VGA5934"

driver.get(URL)
上面的代码打开一个浏览器 session ,该 session 面临 Cloudflare Javascript 挑战。在使用上述开关进行测试期间,这一挑战不会停止。 Cloudflare Ray ID,每个请求的唯一 ID 在我手动终止 session 之前轮换了很多次。
enter image description here
seleniumwire需要获取状态码
下面是一个 headless 模式 Chrome webdriver session ,它还显示了目标 URL 的 403 Forbidden 错误代码。 session 还显示 hcaptcha.com反机器人技术现在正在混合使用。
from seleniumwire import webdriver

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("start-maximized")
chrome_options.add_argument("--headless")
chrome_options.add_argument(
"user-agent=Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36")
chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
chrome_options.add_experimental_option('useAutomationExtension', False)
chrome_options.add_argument("--disable-blink-features=AutomationControlled")

driver = webdriver.Chrome(executable_path='/usr/local/bin/chromedriver', options=chrome_options)
URL = "https://www.cclonline.com/product/334427/GV-N3070AORUS-M-8GD-1-1/Graphics-Cards/Gigabyte-AORUS-GeForce-RTX-3070-MASTER-8GB-Overclocked-Graphics-Card-rev-1-1-/VGA5934"
driver.get(URL)

for request in driver.requests:
print(f'Status Code: {request.response}')
print(f'Host Name: {request.host}')
# output
Status Code: 403
Host Name: www.cclonline.com
-----------------------
Status Code: 200
Host Name: www.cclonline.com
-----------------------
Status Code: 200
Host Name: www.cclonline.com
-----------------------
Status Code: 200
Host Name: www.cclonline.com
-----------------------
Status Code: 200
Host Name: www.cclonline.com
-----------------------
Status Code: 200
Host Name: www.cclonline.com
-----------------------
Status Code: 200
Host Name: www.cclonline.com
-----------------------
Status Code: 200
Host Name: www.cclonline.com
-----------------------
Status Code: 302
Host Name: hcaptcha.com
-----------------------
Status Code: 200
Host Name: newassets.hcaptcha.com
-----------------------
driver.quit()

使用 UI 的标准 Chrome 网络驱动程序 session 显示带有“我是人类”复选框的 iFrame。
enter image description here
如果我手动或使用 selenium session 单击该按钮,则会收到图片验证码提示,这增加了绕过 Cloudflare 保护的复杂性。
enter image description here
cf_clearance cookie

当 Cloudflare CAPTCHA 或 Javascript 挑战得到解决时,会在客户端浏览器中设置 cf_clearance cookie。 cf_clearance cookie 的默认生命周期为 30 分钟,但可由 Cloudflare 客户端配置。
如果您在 Google Chrome 浏览器中手动打开 OP 的目标 URL,您可以使用开发者工具看到 cf_clearance cookie
根据此 session 开始的 UTC 时间和为 cookie 设置的到期日期,似乎 cf_clearance cookie 生存期设置为 60 分钟。
到目前为止,我还没有找到使用 Python 提取此 cookie 的方法。
enter image description here

关于python - 无法从网页中抓取产品标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67887751/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com