马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 康小泡 于 2018-11-2 18:33 编辑
做一个爬微博的from urllib.parse import urlencode
import requests
base_url = 'https://m.weibo.cn/qpi/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)
from pyquery import PyQuery as pq
def parse_page(json):
if json:
items = json.get('data').get('cards')
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')
yield weibo
if __name__ == '__main__':
for page in range(1,11):
json = get_page(page)
results = parse_page(json)
for result in results:
print(result)
from pymongo import MongoClinent
client = MongoClinent()
db = client['weibo']
collection = db['weibo']
def save_to_mongo(result):
if collection.insert(result):
print('Saved to Mongo')
——————————————————————————————————
Traceback (most recent call last):
File "D:/learn/pycharm/exercise/微博.py", line 45, in <module>
for result in results:
File "D:/learn/pycharm/exercise/微博.py", line 31, in parse_page
items = json.get('data').get('cards')
AttributeError: 'NoneType' object has no attribute 'get'
这是要怎么修改啊新手求助谢谢大佬
|