Urllib 请求不能在单独的计算机上工作

Urllib requests not working on separate computer

我正在使用 fiddler 来跟踪 HTTP 请求。

这让我可以使用 urllib 自动填写表格。

它在我使用的 jupyter notebook 上运行良好,并把它交给同事试用。它在他的电脑上不起作用。

我对此完全陌生,所以我可能犯了一个简单的错误。我认为这可能与 cookies 有关 header 也许?

我正在在线表格中填写姓名和邮政编码。

要求:

import urllib.request  as urllib2

req = urllib2.Request("https://carlowcoco.checktheregister.ie/publicpages/Results.aspx")

添加Headers:

req.add_header("Connection", "keep-alive")
req.add_header("Cache-Control", "max-age=0")
req.add_header("Origin", "https://carlowcoco.checktheregister.ie")
req.add_header("Upgrade-Insecure-Requests", "1")
req.add_header("Content-Type", "application/x-www-form-urlencoded")
req.add_header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36 OPR/62.0.3331.116")
req.add_header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8")
req.add_header("Referer", "https://carlowcoco.checktheregister.ie/publicpages/ereg.aspx?CID=4&uiLang=en-GB")
req.add_header("Accept-Encoding", "gzip, deflate, br")
req.add_header("Accept-Language", "en-US,en;q=0.9")
req.add_header("Cookie", "_ga=GA1.2.1485303330.1563803355; _fbp=fb.1.1563803355623.389471504; _gid=GA1.2.1242949638.1567500110; ASP.NET_SessionId_eReg=wbyf1iuvothtmdr0zxq4ypnv; _gat=1")

发送信息:

firstname='john'
lastname='smith'
zipcode='abc123'

# this is where we add the name, surname and zipcode
body = f"__LASTFOCUS=&__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwULLTExODA1MzM2NzFkZI2Y9Vj1N4c71dOJShLXen0Q8nT0&__VIEWSTATEGENERATOR=1627BCCD&__PREVIOUSPAGE=o3Y5pVByrKh5ylQa3zb19RrpXCBCTakCQLkYw24qRyH07uZC4V8-00fT-aZjmROM9Gnkny1RyjaEBGfxfBR95RnY9Dn0zJEhObiGTquHfVvYnOZx0&__EVENTVALIDATION=%2FwEWBwKFwaWxBQLp48u6DgK95LDpBAK62djbDgLthcGDBQL0mu%2BYCwK83r2cAZJf50Jf%2F9CI7cXegRb5oL0hvtD1&ctl00%24MainContent%24TextBoxPostcode={zipcode}&ctl00%24MainContent%24TextBoxFirstName={firstname}&ctl00%24MainContent%24TextBoxSurname={surname}&ctl00%24MainContent%24FormSubmit=Submit"

# convert to bytes object
body = body.encode('utf-8')

# send request and save to response
response = urllib2.urlopen(req, body)

# read response and convert to string
page = response.read()

它没有返回 URL 或 HTTP 错误,而是返回包含文本 <b>An ERROR has occurred. Please try again. If the issue persists, please try again later.</b>\ 的 HTML。

那为什么这在我的电脑上有效,而我的同事却不行?

另外,请问有更好的方法吗? header 看起来很乱。我有一种感觉,可能有一种更简洁的方法来自动填写表单。

如上所述,问题出在 cookie 中的会话 ID。您的同事需要将其替换为他自己的会话 ID 才能正常工作。你应该能够得到一个新的。