req= request.Request(url=url,data=data,headers=headers)
此时会报错,类型不对
报错为“POST data should be bytes or an iterable of bytes...”
后改为如下方法,将body中的data以utf-8编码即可
req= request.Request(url=url,data=data.encode('utf-8'),headers=headers)
请求方法仍然是
response= request.urlopen(req)
当收到response时,使用read()同时解码即可,如下
response.read().decode('utf-8')
网上很多方法中会提到下面这个方法
urllib.parse.urlendcode
这个方法是用在将json格式文件url编码的,当body为字符串时,使用此方法无效,仍然是错误的
一般是这样,用request库获取html内容,然后用正则表达式获取内容。比如:import requests
from bs4 import BeautifulSoup
txt=requests.get("https://www.gov.cn/").text //抓取网页
a=BeautifulSoup(txt,'html.parser') //构建解析器
print(a.body) //获取内容,也可以是a.title或者其他的标记内容
def count_digits(s):count = 0
for c in s:
if c.isdigit():
count += 1
return count
>>>count_digits('xx3ab438k9')
5