### Python3.6 urllib获取网页内容函数
```python
'''
获取网页html内容函数
@param str url 获取目标url地址
@param list post_data 页面post请求数组参数(get请求忽略)
@return str html
'''
def get_page_html(url,post_data={}):
headers = {
'Accept': 'application/json, text/plain, */*',
#'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
'Connection': 'keep-alive',
# 'Content-Length': '14',
'Content-Type': 'application/x-www-form-urlencoded',
'Referer': 'http://www.www.fity.cn',
'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.23 Mobile Safari/537.36'
}
data = urllib.parse.urlencode(data).encode('utf-8')
req = urllib.request.Request(url, headers=headers, data=data)
try:
page = urllib.request.urlopen(req).read()
page = page.decode('utf-8')
except Exception:
page = ''
return page
```
#### 函数使用:
>get_page_html('https://www.fity.cn').replace(' ','').replace('\r\n', '').replace('\t', '')
>get_page_html('https://www.fity.cn', post_data).replace(' ','').replace('\r\n', '').replace('\t', '')
最后更新于 2019-06-27 13:44:40 并被添加「python python3」标签,已有 821 位童鞋阅读过。
本站使用「署名 4.0 国际」创作共享协议,可自由转载、引用,但需署名作者且注明文章出处
相关文章