查看这段代码有没有错误 def countPic(url): print('正在检测图片总数,请稍等.....') pic_num='' t = 0#pn变量,用于拼接Url Url = url + str(t) try: html = requests.get(Url,header,timeout=7) except BaseException: print('请求异常') else: result = html.text #bdFmtDispNum: "约1,050,000", # print(result) flist = re.findall('"bdFmtDispNum":"(.*?)",', result, re.S) # 先利用正则表达式找到图片总数 # print(type(pic_num)) #list # print(type(flist)) for i in flist: # print(i) pic_num+=i # print(pic_num) return pic_num
时间: 2024-01-20 22:02:06 浏览: 74
这段代码可能存在以下错误:
1. 在调用 requests.get() 方法时,header 参数可能未定义。
2. 在调用 re.findall() 方法时,re.S 参数可能未定义。
3. 在对 pic_num 进行字符串拼接时,可能存在类型不匹配的问题。可以将 pic_num 定义为列表,然后使用 append() 方法添加字符串。
建议修正后的代码如下:
```python
import requests
import re
def countPic(url):
print('正在检测图片总数,请稍等.....')
pic_num = []
t = 0 # pn变量,用于拼接Url
Url = url + str(t)
header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
try:
html = requests.get(Url, headers=header, timeout=7)
except BaseException:
print('请求异常')
else:
result = html.text
flist = re.findall('"bdFmtDispNum":"(.*?)",', result, re.S) # 先利用正则表达式找到图片总数
for i in flist:
pic_num.append(i)
return ''.join(pic_num)
```
此代码已经添加了 header 和 re.S 参数,并将 pic_num 定义为列表,最后使用 join() 方法将列表中的所有字符串拼接成一个字符串。
阅读全文
相关推荐

















