本帖最后由 suchocolate 于 2020-11-15 10:57 编辑
这个服务器认为输入一种参数就够(data或params,注意两种是不同的,前者作为http数据,后者放到request header请求中),否则不给你正确的数据。
你的URL中已包含参数,所以去掉data即可。
import urllib.request
import urllib.parse
def main():
url = "http://hngcjs.hnjs.gov.cn/company/Aqscxkz?tyshxydm=914107285976277372&qymc=%E4%B8%80%E6%81%92%E5%BB%BA%E8%AE%BE%E9%9B%86%E5%9B%A2%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8"
head = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 '
'Safari/537.36 Core/1.70.3823.400 QQBrowser/10.7.4307.400'}
req = urllib.request.Request(url=url, headers=head)
res = urllib.request.urlopen(req)
html = res.read().decode('utf-8')
print(html)
if __name__ == '__main__':
main()
或者你改URL,把data带上:import urllib.request
import urllib.parse
def main():
url = "http://hngcjs.hnjs.gov.cn/company/Aqscxkz"
head = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 '
'Safari/537.36 Core/1.70.3823.400 QQBrowser/10.7.4307.400'}
data = {'tyshxydm': '914107285976277372', 'qymc': '一恒建设集团有限公司'}
data = urllib.parse.urlencode(data).encode('utf-8')
req = urllib.request.Request(url=url, data=data, headers=head)
res = urllib.request.urlopen(req)
html = res.read().decode('utf-8')
print(html)
if __name__ == '__main__':
main()
如果参数需要变换,可以用urlencode随时合成URL,注意base_url结尾有个问号是用来分隔域名和参数的:import urllib.request
import urllib.parse
from urllib.parse import urlencode
def main():
base_url = "http://hngcjs.hnjs.gov.cn/company/Aqscxkz?"
head = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 '
'Safari/537.36 Core/1.70.3823.400 QQBrowser/10.7.4307.400'}
params = {'tyshxydm': '914107285976277372', 'qymc': '一恒建设集团有限公司'}
url = base_url + urlencode(params)
req = urllib.request.Request(url=url, headers=head)
res = urllib.request.urlopen(req)
html = res.read().decode('utf-8')
print(html)
if __name__ == '__main__':
main()
|