|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 九千 于 2020-5-7 21:09 编辑
代码全部来自:=https://www.makcyun.top/2018/10/12/web_scraping_withpython6.html]
- import requests
- import re
- import json
- import csv
- #定义一个get_table()方法来输出抓取的第一页表格内容
- def get_table():
-
- params = { #params为url请求中所包含的参数
- 'type':'CWBB_LRB20',#表格类型,LRB为利润表缩写,必须
- 'token':'70f12f2f4f091e459a279469fe49eca5',#访问令牌,必须
- 'st':'noticedate',
- 'sr':-1,
- 'p':1,
- 'ps':50,
- 'js':'var YlIfdEKv={pages:(tp),data: (x),font:(font)}',
- 'filter':"(securitytypecode='058001001')(reportdate=^2018-06-30^)"#筛选条件
- #'rt':52961251 可以不用
- }
- #params参数设置好之后,将url和params参数一起传进requests.get()方法中,这样就构造好了请求连接
- url='http://dcfm.eastmoney.com/em_mutisvcexpandinterface/api/js/get?type=CWBB_LRB20&token=70f12f2f4f091e459a279469fe49eca5&st=noticedate&sr=-1&p=2&ps=50&js=var%20svbCesOb={pages:(tp),data:%20(x),font:(font)}&filter=(securitytypecode=%27058001001%27)(reportdate=^2018-06-30^)&rt=52961271'
- #仅使用http://dcfm.eastmoney.com/em_mutisvcexpandinterface/api/js/get?搜索出来的页面只显示hello world ,用了这么长的才能搜索出来显示的是数据
- response = requests.get(url,params=params).text
- #print(response)
- #get_table()
- #正则表达式提取表格
- #确定页数
- page_all = re.search(r'var.*?{pages:(\d+),data:.*?',response) #用\d+匹配页数中的数值
- #page_all=re.search(pat,response) #用re.search()方法提取出前面匹配的数值
- #print(type(page_all))
- print(page_all.group(1)) #group(1)表示输出第一个结果,这里就是()中的页数
-
- #提取出list,可以用json.dumps和json.loads
- #pattern = re.compile(r'var.*?data:(.*)}',re.S)
-
- items = re.search(r'var.*?data:(.*)}',response) #re.search()返回的结果是字符串类型
- data=items.group(1)
- #print(type(data)) #注释掉的是用于检测类型
-
- #print(type(list(data)))
- data=data[0]
- #print(type(data))
- #print(data[0])
- for d in data:
- with open('eastmoney.csv','a',encoding='utf-8',newline='') as f:
- w = csv.writer(f)
- w.writerow(d.values)
-
- try:
- data=json.loads(data)
- except json.decoder.JSONDecodeError as reason:
- print('九千岁',reason)
- print(type(data))
- print(data[0])
- for d in data:
- with open('eastmoney.csv','a',encoding='utf-8',newline='') as f:
- w = csv.writer(f)
- w.writerow(d.values)
- get_table()
复制代码
我是想要将请求网页得到的Response,利用正则解析后获得的一段str数据,转换为list,这样方便后面写入表格,
但在使用json.loads()方法转换时出现异常,想请问一下这是为什么,应该怎么解决?从网页解析出来的数据 |
|