[英]why can't I access full html of this page using urllib, beautifulsoup
[英]Why can't I access Digikey's website through urllib?
我在這里遵循指南:
對於前幾個示例,一切正常:
import urllib.request
html = urllib.request.urlopen('https://arstechnica.com').read()
print(html)
和
import urllib.request
headers = {}
headers['User-Agent'] = "Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:48.0) Gecko/20100101 Firefox/48.0"
req = urllib.request.Request('https://arstechnica.com', headers = headers)
html = urllib.request.urlopen(req).read()
print(html)
但是,如果我將“arstechnica”替換為“digikey”,則該 urllib 請求總是會超時。 但是可以通過瀏覽器輕松訪問該網站。 這是怎么回事?
大多數網站都會嘗試保護自己免受不需要的機器人的侵害。 如果他們檢測到可疑流量,他們可能會在未正確關閉連接的情況下決定停止響應(讓您掛起)。 一些網站在檢測機器人方面比其他網站更復雜。
Firefox 48.0 於 2016 年發布,因此 Digikey 很明顯您可能在欺騙 header 信息。 還有一些瀏覽器通常會發送的附加標頭,而您的腳本不會。
在 Firefox 中,如果您打開開發者工具和 go 到網絡監視器選項卡,您可以檢查請求以查看它發送的標頭,然后復制這些以更好地模仿典型瀏覽器的行為。
import urllib.request
headers = {
"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.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",
"Upgrade-Insecure-Requests": "1"
}
req = urllib.request.Request('https://www.digikey.com', headers = headers)
html = urllib.request.urlopen(req).read()
print(html)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.