下面代码运行后文档内只有标题,没有内容,请帮我找一下原因 # -*- coding: utf-8 -*- import urllib.request import re import pandas as pd import time def getdata(url): req = urllib.request.Request(url) req.add_header('User-Agent', ' Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36') data = urllib.request.urlopen(req).read().decode('utf-8') str1 = str(data) pat = '''<tr> <td>(.*?)</td> <td>(.*?)</td> <td>(.*?)</td> <td>(.*?)</td> <td>.?</td> </tr>''' result = re.compile(pat).findall(str1) return result if __name__ == '__main__': for i in range(2018, 2020): print('正在收集第%d年数据' % i) rank = [] country = [] zhou = [] total = [] url = 'https://www.kuaiyilicai.com/stats/global/yearly/g_gdp/' + str(i) + '.html' data = getdata(url) for j in range(0, len(data)): rank.append(data[j][0]) country.append(data[j][1]) zhou.append(data[j][2]) total.append(data[j][3]) dataframe = pd.DataFrame({'排名': rank, '国家/地区': country, '所在洲': zhou, 'GDP(美元计)': total}) with open(str(i) + "年世界gdp排名.csv", mode="w", encoding="utf_8_sig") as f: dataframe.to_csv(f, index=False, sep=',') print(i, '年数据收集完成')
时间: 2024-04-28 13:21:54 浏览: 148
这个代码的问题可能是在正则表达式的匹配上。你可以把这一行代码:
```
pat = '''<tr> <td>(.*?)</td> <td>(.*?)</td> <td>(.*?)</td> <td>(.*?)</td> <td>.?</td> </tr>'''
```
修改为:
```
pat = '''<tr> <td>(.*?)</td> <td>(.*?)</td> <td>(.*?)</td> <td>(.*?)</td> <td>(.*?)</td> </tr>'''
```
原因是因为在该网页中,每一行的最后一个数据被包含在了 `<td>` 标签内,而原来的正则表达式并没有匹配到该数据。
相关问题
修改后,运行下面代码运行后文档内只有列索引,没有内容,请帮我找一下原因 # -*- coding: utf-8 -*- import urllib.request import re import pandas as pd import time def getdata(url): req = urllib.request.Request(url) req.add_header('User-Agent', ' Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36') data = urllib.request.urlopen(req).read().decode('utf-8') str1 = str(data) pat = '''<tr> <td>(.*?)</td> <td>(.*?)</td> <td>(.*?)</td> <td>(.*?)</td> <td>(.*?)</td> </tr>''' result = re.compile(pat).findall(str1) return result if __name__ == '__main__': for i in range(2018, 2020): print('正在收集第%d年数据' % i) rank = [] country = [] zhou = [] total = [] url = 'https://www.kuaiyilicai.com/stats/global/yearly/g_gdp/' + str(i) + '.html' data = getdata(url) for j in range(0, len(data)): rank.append(data[j][0]) country.append(data[j][1]) zhou.append(data[j][2]) total.append(data[j][3]) dataframe = pd.DataFrame({'排名': rank, '国家/地区': country, '所在洲': zhou, 'GDP(美元计)': total}) with open(str(i) + "年世界gdp排名.csv", mode="w", encoding="utf_8_sig") as f: dataframe.to_csv(f, index=False, sep=',') print(i, '年数据收集完成')
这个问题可能是因为 `pandas.DataFrame` 对象创建成功,但在写入 csv 文件时出现了问题。你可以在写文件时添加一个参数 `header=True`,以确保写入文件时包含列名。修改后的写入文件的代码如下所示:
```
with open(str(i) + "年世界gdp排名.csv", mode="w", encoding="utf_8_sig") as f:
dataframe.to_csv(f, index=False, header=True, sep=',')
```
如果问题仍然存在,你可以尝试检查生成的 `pandas.DataFrame` 对象中是否有数据。
#!/usr/local/bin/python3 # -*- coding: utf-8 -*- # @Time : 2023/6/11 14:19 # @Author : 志在星空 # @File : jietu12.py # @Software: PyCharm import base64 import urllib import requests import json API_KEY = "jHxdMDf2bhEPxcG6zFoRUejo" SECRET_KEY = "QF5GO9eLQncG2Zr1MKrxLOWvKAkAtVfI" def main(): # 发送 OCR 请求并获取响应 url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general?access_token=" + get_access_token() # payload = 'image=%2F9j%2F4AAQ' headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' } image_path = "11.jpg" with open(image_path, "rb") as image_file: image_data = image_file.read() response = requests.post(url, headers=headers, data=image_data) # response = requests.request("POST", url, headers=headers, data=payload) # 解析响应并提取 words_result 中的所有 words 字段 result = json.loads(response.text) print(result) # words_list = [item['words'] for item in result['words_result']] # print(words_list) # # # 打印所有提取到的内容 # for words in words_list: # print(words) def get_file_content_as_base64(path, urlencoded=False): """ 获取文件base64编码 :param path: 文件路径 :param urlencoded: 是否对结果进行urlencoded :return: base64编码信息 """ with open(path, "rb") as f: content = base64.b64encode(f.read()).decode("utf8") if urlencoded: content = urllib.parse.quote_plus(content) return content def get_access_token(): """ 使用 AK,SK 生成鉴权签名(Access Token) :return: access_token,或是None(如果错误) """ url = "https://aip.baidubce.com/oauth/2.0/token" params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY} return str(requests.post(url, params=params).json().get("access_token")) if __name__ == '__main__': main()运行出现{'log_id': 1667825949995168966, 'error_msg': 'param image not exist', 'error_code': 216101},怎么办
根据API的响应信息,错误信息为"param image not exist",也就是说API无法找到你指定的图片文件。请确保文件路径是正确的,并且文件名和扩展名的大小写与实际文件匹配。如果文件名或路径错误,将导致API无法找到该文件并出现上述错误。如果你确定文件路径和文件名正确无误,那么你可以检查一下API文档以确定API对请求的其他要求,例如请求头、请求参数等是否正确。此外,你还可以尝试使用图片的base64编码代替图片路径传递给API,方法详见上面代码中的`get_file_content_as_base64`函数。
阅读全文
相关推荐
















