1 Star 1 Fork 5

zhenghua / Scrpay

forked from 梁新斌 / Scrpay 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
WeiboAjax.py 3.13 KB
一键复制 编辑 原始数据 按行查看 历史
梁新斌 提交于 2019-01-10 16:33 . 修改注释
#微博数据爬取 ,使用ajax爬取数据
from urllib.parse import urlencode
import requests
from pyquery import PyQuery as pq
from urllib.parse import urlencode
import requests
base_url = 'https://m.weibo.cn/api/container/getIndex?'
headers = {
'Host': 'm.weibo.cn',
'Referer': 'https://m.weibo.cn/u/2830678474',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
'X-Requested-With': 'XMLHttpRequest',
}
def get_page(page):
params = {
'type': 'uid',
'value': '2830678474',
'containerid': '1076032830678474',
'page': page
}
url = base_url + urlencode(params)
try:
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.json()
except requests.ConnectionError as e:
print('Error', e.args)
#使用yield一次返回一个,数据量多的时候优势明显
def parse_page_yield(json):
if json:
items = json.get('data').get('cards')
wblist = []
for item in items:
item = item.get('mblog')
weibo = {}
weibo['id'] = item.get('id')
weibo['text'] = pq(item.get('text')).text()
weibo['attitudes'] = item.get('attitudes_count')
weibo['comments'] = item.get('comments_count')
weibo['reposts'] = item.get('reposts_count')
#一个页面的json中包含10条微博,如果使用return,则每次只能得到最上面的一条微博。
#使用yield每次取10条中的1条返回,第二次接着上一次的取,每次只取一条,返回一条,
#使用return需要将每次循环生成的字典weibo存入列表中作为一个元素,在10条都循环取完之后一次性返回
#列表数据量大时,使用yield优势明显
# wblist.append(weibo)
yield weibo
# return wblist
#用list一次性返回
def parse_page_list(json):
if json:
items = json.get('data').get('cards')
wblist = []
for item in items:
item = item.get('mblog')
weibo = {}
weibo['id'] = item.get('id')
weibo['text'] = pq(item.get('text')).text()
weibo['attitudes'] = item.get('attitudes_count')
weibo['comments'] = item.get('comments_count')
weibo['reposts'] = item.get('reposts_count')
#一个页面的json中包含10条微博,如果使用return,则每次只能得到最上面的一条微博。
#使用yield每次取10条中的1条返回,第二次接着上一次的取,每次只取一条,返回一条,
#使用return需要将每次循环生成的字典weibo存入列表中作为一个元素,在10条都循环取完之后一次性返回
#列表数据量大时,使用yield优势明显
wblist.append(weibo)
return wblist
if __name__ == '__main__':
for page in range(3, 4):
json = get_page(page)
results = parse_page_yield(json)
for result in results:
print(result.get('id'))
Python
1
https://gitee.com/zhenghua0501/Scrpay.git
git@gitee.com:zhenghua0501/Scrpay.git
zhenghua0501
Scrpay
Scrpay
master

搜索帮助