⑴ 如何通過python調用新浪微博的API來爬取數據
先上結論,通過公開的api如果想爬到某大v的所有數據,需要滿足以下兩個條件:
1、在你的爬蟲開始運行時,該大v的所有微博發布量沒有超過回溯查詢的上限,新浪是2000,twitter是3200。
2、爬蟲程序必須不間斷運行。
新浪微博的api基本完全照搬twitter,其中介面的參數特性與底層的NoSQL密不可分,建議先看點Nosql資料庫的設計理念有助於更好的理解api設計。
一般來說,如果決定爬某個大v,第一步先試獲取該用戶的基本信息,中間會包含一條最新的status,記下其中的id號作為基準,命名為baseId。
介面中最重要的兩個參數:
since_id:返回ID比since_id大的微博(即比since_id時間晚的微博),默認為0。
max_id:返回ID小於或等於max_id的微博,默認為0。
出於各種原因,獲取statuses的介面,固定為按id降序排列(scan_index_forward=false),即最新的statuses返回在前。假設該微博第一天上線,就一個用戶,發了一百條,id是1到100。而你在該用戶發了第50條的時候開始運行的爬蟲,即baseId=50。
⑵ python怎麼爬取簡書用戶名
初步的思路
今天在用Scrapy寫代碼的時候,對網頁的結構也有了大致的分析,再加上之前羅羅攀的思路,初步我是通過專題入口
熱門專題
image.png
image.png
專題管理員 (一般粉絲、文章、字數、收獲喜歡、這幾項數據都非常漂亮)
image.png
image.png
以上紅框里的數據項就是我需要爬取的欄位
但是以上的思路存在一點的問題:
存在一些簡書用戶並不是一些熱門專題的管理員,但是其人氣粉絲量也很高,這個思路可能無法將這些用戶爬取下來
進階的思路
熱門專題
專題關注的人
專題關注的人的動態
推薦作者 粉絲信息
image.png
image.png
image.png
優點:
數據大而全,基本包含了99%的用戶(個人猜測,不嚴謹)
缺點:
因為許多用戶不止關注一個專題,而且其中包含了大量的新注冊用戶(數據很多為空),並且也有大量重復數據需要去重
代碼部分:
jianshu.py 還在調試階段,待更新...
# -*- coding: utf-8 -*-
import sys
import json
import requests
import scrapy
import re
from lxml import etree
from scrapy.http import Request
reload(sys)
sys.path.append('..')
sys.setdefaultencoding('utf-8')
class jianshu(scrapy.Spider):
name = 'jianshu'
# topic_category = ['city']
topic_category = ['recommend', 'hot', 'city']
base_url = 'lections?page=%s&order_by=%s'
cookies={
'UM_distinctid': '15b89d53a930-02ab95f11ccae2-51462d15-1aeaa0-15b89d53a9489b',
'CNZZDATA1258679142': '1544557204-1492664886-%7C1493280769',
'_session_id': '%3D%3D--',
'remember_user_token':'Q3LjYwODEwNzgiXQ%3D%3D--',
'_ga': 'GA1.2.2016948485.1492666105',
'_gid': 'GA1.2.382495.1494550475',
'Hm_lpvt_': '1494550475',
'Hm_lvt_': '1494213432,1494213612,1494321303,1494387194'
}
headers = {
'Accept-Encoding': 'gzip, deflate, sdch',
'Accept - Language': 'zh - CN, zh;q = 0.8',
'Connection': 'close',
'Cookie': 'UM_distinctid=15b89d53a930-02ab95f11ccae2-51462d15-1aeaa0-15b89d53a9489b; CNZZDATA1258679142=1544557204-1492664886-%7C1493280769; remember_user_token=Q3LjYwODEwNzgiXQ%3D%3D--; _ga=GA1.2.2016948485.1492666105; _gid=GA1.2.824702661.1494486429; _gat=1; Hm_lvt_=1494213432,1494213612,1494321303,1494387194; Hm_lpvt_=1494486429; _session_id=%3D%3D--',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36',
'Host':'www.jianshu.com',
"X-Requested-With": 'XMLHttpRequest'
}
def get_total_page(self):
#獲取專題總頁數 包含3個字典的列表 [{"hot": xx}, {"recommend":xx}, {"city": xx}]
total_page_list = []
for order in self.topic_category:
order = order.decode('utf-8')
total_page = 100
dict = {}
for page in range(1, total_page):
url = self.base_url % (page, order)
html = requests.get(url, headers=self.headers).content
selector = etree.HTML(html)
#print html
try:
elements = selector.xpath('//*[@id="list-container"]/div[1]/div/h4/a/text()')[0]
if elements is not Exception:
continue
except Exception :
dict['total_page'] = page - 1
dict['category'] = order
break
total_page_list.append(dict)
return total_page_list
def get_topic_info(self):
#獲取專題信息
topic_info_list = []
total_page_list = self.get_total_page()
base_url = self.base_url
for dict in total_page_list:
category = dict['category']
total_page = int(dict['total_page'])
for page in range(1, total_page + 1):
url = base_url % (page, category)
html = requests.get(url, headers=self.headers,cookies=self.cookies).content
selector = etree.HTML(html)
topic_href = selector.xpath('//*[@id="list-container"]')[0]
for href in topic_href:
dict = {}
topic_name = href.xpath('./div/h4/a/text()')[0]
topic_url = "www.jianshu.com" + href.xpath('./div/h4/a/@href')[0]
topic_img_url = href.xpath('./div/a/img/@src')[0]
img_num = topic_img_url.split("/")[5]
dict['topic_name'] = topic_name
dict['topic_url'] = topic_url
#
dict['img_num'] = img_num
topic_info_list.append(dict)
return topic_info_list
def get_topic_admin_info(self):
#獲取管理員信息
topic_admin_info_list = []
topic_info_list = self.get_topic_info()
for d in topic_info_list:
img_num = str(d['img_num'])
base_url = "s/editors_and_subscribers" % img_num
base_url_response = requests.get(base_url, headers=self.headers, cookies=self.cookies)
json_data_base = json.loads(base_url_response.text.decode('utf-8'))
editors_total_pages = json_data_base['editors_total_pages']
for page in range(1, int(editors_total_pages) + 1):
if page == 1:
editors = json_data_base['editors']
for editor in editors:
dict = {}
dict['nickname'] = editor['nickname']
dict['slug'] = editor['slug']
topic_admin_info_list.append(dict)
else:
try:
url = "}/editors?page={}".format(img_num, page)
response = requests.get(url,headers=self.headers,cookies=self.cookies)
json_data = json.loads(response.text.decode('utf-8'))
editors = json_data['editors']
for editor in editors:
dict = {}
dict['nickname'] = editor['nickname']
dict['slug'] = editor['slug']
topic_admin_info_list.append(dict)
except Exception:
pass
return topic_admin_info_list
def get_followers_following_list(self):
# 獲取管理員粉絲列表
followers_list = []
topic_admin_list = self.get_topic_admin_info()
followers_base_url = "s/%s/followers"
for dict in topic_admin_list:
url = followers_base_url % dict['slug']
headers = self.headers
headers['Referer'] = url
headers['DNT'] = '1'
response = requests.get(url, headers=headers, cookies=self.cookies).content
total_followers = re.fi
⑶ 如何用 Python 爬取社交網路
從資料庫中拿出用戶id列表,批量爬取一批用戶id的微博數據,然後保存相應的內容到資料庫中。可以動態爬取,每天開個定時啟動任務,自動會爬取數據有無更新,有更新則更新資料庫。
如需要爬取單個用戶,注釋掉那部分代碼即可。
我沒有用Scrapy框架,手寫的,解析並不復雜,用的BS4,注意要手動登錄,獲取cookie。
微博反爬策略還是比較強的,用API的方式限制真的太多了,完全做不到想要什麼就爬什麼。
PC端的數據比較難分析,它把數據放到script標簽塊中,用瀏覽器去渲染出來的,直接抓是拿不到的,要分析script標簽塊。
最好爬的一種就是移動端網頁,http://weibo.cn,數據格式簡單,限制也少。
⑷ python可以爬取個人信息嗎
只能爬取公示出來的信息,不能爬取未公示的信息
⑸ 怎樣用python爬新浪微博大V所有數據
我是個微博重度用戶,工作學習之餘喜歡刷刷timeline看看有什麼新鮮事發生,也因此認識了不少高質量的原創大V,有分享技術資料的,比如好東西傳送門;有時不時給你一點人生經驗的,比如石康;有高產的段子手,比如銀教授;有黃圖黃段子小能手,比如阿良哥哥木木蘿希木初犬餅…
好吧,我承認,爬黃圖黃段子才是我的真實目的,前三個是掩人耳目的…(捂臉,跑開)
另外說點題外話,我一開始想使用Sina Weibo API來獲取微博內容,但後來發現新浪微博的API限制實在太多,大家感受一下:
iTerm
小問題:在我的測試中,有的時候會出現圖片下載失敗的問題,具體原因還不是很清楚,可能是網速問題,因為我宿舍的網速實在太不穩定了,當然也有可能是別的問題,所以在程序根目錄下面,我還生成了一個userid_imageurls的文本文件,裡面存儲了爬取的所有圖片的下載鏈接,如果出現大片的圖片下載失敗,可以將該鏈接群一股腦導進迅雷等下載工具進行下載。
另外,我的系統是OSX EI Capitan10.11.2,Python的版本是2.7,依賴庫用sudo pip install XXXX就可以安裝,具體配置問題可以自行stackoverflow,這里就不展開講了。
下面我就給出實現代碼(嚴肅臉)
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#-*-coding:utf8-*-
import re
import string
import sys
import os
import urllib
import urllib2
from bs4 import BeautifulSoup
import requests
from lxml import etree
reload(sys)
sys.setdefaultencoding('utf-8')
if(len(sys.argv) >=2):
user_id = (int)(sys.argv[1])
else:
user_id = (int)(raw_input(u"請輸入user_id: "))
cookie = {"Cookie": "#your cookie"}
url = 'd?filter=1&page=1'%user_id
html = requests.get(url, cookies = cookie).content
selector = etree.HTML(html)
pageNum = (int)(selector.xpath('//input[@name="mp"]')[0].attrib['value'])
result = ""
urllist_set = set()
word_count = 1
image_count = 1
print u'爬蟲准備就緒...'
for page in range(1,pageNum+1):
#獲取lxml頁面
url = 'hu/%d?filter=1&page=%d'%(user_id,page)
lxml = requests.get(url, cookies = cookie).content
#文字爬取
selector = etree.HTML(lxml)
content = selector.xpath('//span[@class="ctt"]')
for each in content:
text = each.xpath('string(.)')
if word_count >= 4:
text = "%d :"%(word_count-3) +text+" "
else :
text = text+" "
result = result + text
word_count += 1
#圖片爬取
soup = BeautifulSoup(lxml, "lxml")
urllist = soup.find_all('a',href=re.compile(r'^mblog/oripic',re.I))
first = 0
for imgurl in urllist:
urllist_set.add(requests.get(imgurl['href'], cookies = cookie).url)
image_count +=1
fo = open("/Users/Personals/%s"%user_id, "wb")
fo.write(result)
word_path=os.getcwd()+'/%d'%user_id
print u'文字微博爬取完畢'
link = ""
fo2 = open("/Users/Personals/%s_imageurls"%user_id, "wb")
for eachlink in urllist_set:
link = link + eachlink +" "
fo2.write(link)
print u'圖片鏈接爬取完畢'
if not urllist_set:
print u'該頁面中不存在圖片'
else:
#下載圖片,保存在當前目錄的pythonimg文件夾下
image_path=os.getcwd()+'/weibo_image'
if os.path.exists(image_path) is False:
os.mkdir(image_path)
x=1
for imgurl in urllist_set:
temp= image_path + '/%s.jpg' % x
print u'正在下載第%s張圖片' % x
try:
urllib.urlretrieve(urllib2.urlopen(imgurl).geturl(),temp)
except:
print u"該圖片下載失敗:%s"%imgurl
x+=1
print u'原創微博爬取完畢,共%d條,保存路徑%s'%(word_count-4,word_path)
print u'微博圖片爬取完畢,共%d張,保存路徑%s'%(image_count-1,image_path)
⑹ 如何用python爬取一本書的評論用戶
京東圖書評論有非常豐富的信息,這裡面就包含了購買日期、書名、作者、好評、中評、差評等等。以購買日期為例,使用Python + Mysql的搭配進行實現,程序不大,才100行。相關的解釋我都在程序里加註了:
fromseleniumimportwebdriver
frombs4importBeautifulSoup
importre
importwin32com.client
importthreading,time
importMySQLdb
defmydebug():
driver.quit()
exit(0)
defcatchDate(s):
"""頁面數據提取"""
soup=BeautifulSoup(s)
z=[]
globalnowtimes
m=soup.findAll("div",class_="date-buy")
forobjinm:
try:
tmp=obj.find('br').contents
exceptException,e:
continue
if(tmp!=""):
z.append(tmp)
nowtimes+=1
returnz
defgetTimes(n,t):
"""獲取當前進度"""
return"當前進度為:"+str(int(100*n/t))+"%"
#———————————————————————————————————|程序開始|—————————————————————————————————
#確定圖書大類
cate={"3273":"歷史","3279":"心理學","3276":"政治軍事","3275":"國學古籍","3274":"哲學宗教","3277":"法律","3280":"文化","3281":"社會科學"}
#斷點續抓
num1=input("bookid:")
num2=input("pagenumber:")
#生成圖書大類鏈接,共需17355*20=347100次
totaltimes=347100.0
nowtimes=0
#開啟webdirver的PhantomJS對象
#driver=webdriver.PhantomJS()
driver=webdriver.Ie('C:Python27ScriptsIEDriverServer')
#driver=webdriver.Chrome('C:Python27Scriptschromedriver')
#讀出Mysql中的評論頁面,進行抓取
# 連接資料庫
try:
conn=MySQLdb.connect(host='localhost',user='root',passwd='',db='jd')
exceptException,e:
printe
sys.exit()
# 獲取cursor對象
cursor=conn.cursor()
sql="SELECT * FROM booknew ORDER BY pagenumber DESC"
cursor.execute(sql)
alldata=cursor.fetchall()
flag=0
flag2=0
# 如果有數據返回就循環輸出,htt/review/10178500-1-154.html
ifalldata:
forrecinalldata:
#rec[0]--bookid,rec[1]--cateid,rec[2]--pagenumber
if(rec[0]!=str(num1)andflag==0):
continue
else:
flag=1
forpinrange(num2,rec[2]):
if(flag2==0):
num2=0
flag2=1
p+=1
link="htteview/"+rec[0]+"-1-"+str(p)+".html"
#抓網頁
driver.get(link)
html=driver.page_source
#抓評論
buydate=catchDate(html)
#寫入資料庫
forzinbuydate:
sql="INSERT INTO ljj (id, cateid, bookid, date) VALUES (NULL, '"+rec[0]+"','"+rec[1]+"','"+z[0]+"');"
try:
cursor.execute(sql)
exceptException,e:
printe
conn.commit()
printgetTimes(nowtimes,totaltimes)
driver.quit()
cursor.close()
conn.close()
京東圖書評論有非常豐富的信息,這裡面就包含了購買日期、書名、作者、好評、中評、差評等等。以購買日期為例,使用Python + Mysql的搭配進行實現,程序不大,才100行。相關的解釋我都在程序里加註了:
fromseleniumimportwebdriver
frombs4importBeautifulSoup
importre
importwin32com.client
importthreading,time
importMySQLdb
defmydebug():
driver.quit()
exit(0)
defcatchDate(s):
"""頁面數據提取"""
soup=BeautifulSoup(s)
z=[]
globalnowtimes
m=soup.findAll("div",class_="date-buy")
forobjinm:
try:
tmp=obj.find('br').contents
exceptException,e:
continue
if(tmp!=""):
z.append(tmp)
nowtimes+=1
returnz
defgetTimes(n,t):
"""獲取當前進度"""
return"當前進度為:"+str(int(100*n/t))+"%"
#———————————————————————————————————|程序開始|—————————————————————————————————
#確定圖書大類
cate={"3273":"歷史","3279":"心理學","3276":"政治軍事","3275":"國學古籍","3274":"哲學宗教","3277":"法律","3280":"文化","3281":"社會科學"}
#斷點續抓
num1=input("bookid:")
num2=input("pagenumber:")
#生成圖書大類鏈接,共需17355*20=347100次
totaltimes=347100.0
nowtimes=0
#開啟webdirver的PhantomJS對象
#driver=webdriver.PhantomJS()
driver=webdriver.Ie('C:Python27ScriptsIEDriverServer')
#driver=webdriver.Chrome('C:Python27Scriptschromedriver')
#讀出Mysql中的評論頁面,進行抓取
# 連接資料庫
try:
conn=MySQLdb.connect(host='localhost',user='root',passwd='',db='jd')
exceptException,e:
printe
sys.exit()
# 獲取cursor對象
cursor=conn.cursor()
sql="SELECT * FROM booknew ORDER BY pagenumber DESC"
cursor.execute(sql)
alldata=cursor.fetchall()
flag=0
flag2=0
# 如果有數據返回就循環輸出,httreview/10178500-1-154.html
ifalldata:
forrecinalldata:
#rec[0]--bookid,rec[1]--cateid,rec[2]--pagenumber
if(rec[0]!=str(num1)andflag==0):
continue
else:
flag=1
forpinrange(num2,rec[2]):
if(flag2==0):
num2=0
flag2=1
p+=1
link="ht.com/review/"+rec[0]+"-1-"+str(p)+".html"
#抓網頁
driver.get(link)
html=driver.page_source
#抓評論
buydate=catchDate(html)
#寫入資料庫
forzinbuydate:
sql="INSERT INTO ljj (id, cateid, bookid, date) VALUES (NULL, '"+rec[0]+"','"+rec[1]+"','"+z[0]+"');"
try:
cursor.execute(sql)
exceptException,e:
printe
conn.commit()
printgetTimes(nowtimes,totaltimes)
driver.quit()
cursor.close()
conn.close()
⑺ 如何用 Python 爬取需要登錄的網站
步驟一:研究該網站
打開登錄頁面
進入以下頁面 「bitbucket.org/account/signin」。你會看到如下圖所示的頁面(執行注銷,以防你已經登錄)
仔細研究那些我們需要提取的詳細信息,以供登錄之用
在這一部分,我們會創建一個字典來保存執行登錄的詳細信息:
1. 右擊 「Username or email」 欄位,選擇「查看元素」。我們將使用 「name」 屬性為 「username」 的輸入框的值。「username」將會是 key 值,我們的用戶名/電子郵箱就是對應的 value 值(在其他的網站上這些 key 值可能是 「email」,「 user_name」,「 login」,等等)。
2. 右擊 「Password」 欄位,選擇「查看元素」。在腳本中我們需要使用 「name」 屬性為
「password」 的輸入框的值。「password」 將是字典的 key 值,我們輸入的密碼將是對應的 value
值(在其他網站key值可能是 「userpassword」,「loginpassword」,「pwd」,等等)。
3. 在源代碼頁面中,查找一個名為 「csrfmiddlewaretoken」 的隱藏輸入標簽。「csrfmiddlewaretoken」
將是 key 值,而對應的 value 值將是這個隱藏的輸入值(在其他網站上這個 value 值可能是一個名為 「csrftoken」,「 authenticationtoken」 的隱藏輸入值)。列如:「」。
最後我們將會得到一個類似這樣的字典:
Python
payload = {
"username": "<USER NAME>",
"password": "<PASSWORD>",
"csrfmiddlewaretoken": "<CSRF_TOKEN>"
}
1
2
3
4
5
payload = {
"username": "<USER NAME>",
"password": "<PASSWORD>",
"csrfmiddlewaretoken": "<CSRF_TOKEN>"
}
請記住,這是這個網站的一個具體案例。雖然這個登錄表單很簡單,但其他網站可能需要我們檢查瀏覽器的請求日誌,並找到登錄步驟中應該使用的相關的 key 值和 value 值。
步驟2:執行登錄網站
對於這個腳本,我們只需要導入如下內容:
Python
import requests
from lxml import html
1
2
import requests
from lxml import html
首先,我們要創建 session 對象。這個對象會允許我們保存所有的登錄會話請求。
Python
session_requests = requests.session()
1
session_requests = requests.session()
第二,我們要從該網頁上提取在登錄時所使用的 csrf 標記。在這個例子中,我們使用的是 lxml 和 xpath 來提取,我們也可以使用正則表達式或者其他的一些方法來提取這些數據。
Python
login_url = "https://bitbucket.org/account/signin/?next=/"
result = session_requests.get(login_url)
tree = html.fromstring(result.text)
authenticity_token = list(set(tree.xpath("//input[@name='csrfmiddlewaretoken']/@value")))[0]
1
2
3
4
5
login_url = "https://bitbucket.org/account/signin/?next=/"
result = session_requests.get(login_url)
tree = html.fromstring(result.text)
authenticity_token = list(set(tree.xpath("//input[@name='csrfmiddlewaretoken']/@value")))[0]
**更多關於xpath 和lxml的信息可以在這里找到。
接下來,我們要執行登錄階段。在這一階段,我們發送一個 POST 請求給登錄的 url。我們使用前面步驟中創建的 payload 作為 data 。也可以為該請求使用一個標題並在該標題中給這個相同的 url 添加一個參照鍵。
Python
result = session_requests.post(
login_url,
data = payload,
headers = dict(referer=login_url)
)
1
2
3
4
5
result = session_requests.post(
login_url,
data = payload,
headers = dict(referer=login_url)
)
步驟三:爬取內容
現在,我們已經登錄成功了,我們將從 bitbucket dashboard 頁面上執行真正的爬取操作。
Python
url = 'https://bitbucket.org/dashboard/overview'
result = session_requests.get(
url,
headers = dict(referer = url)
)
1
2
3
4
5
url = 'https://bitbucket.org/dashboard/overview'
result = session_requests.get(
url,
headers = dict(referer = url)
)
為了測試以上內容,我們從 bitbucket dashboard 頁面上爬取了項目列表。我們將再次使用
xpath 來查找目標元素,清除新行中的文本和空格並列印出結果。如果一切都運行 OK,輸出結果應該是你 bitbucket 賬戶中的
buckets / project 列表。
Python
tree = html.fromstring(result.content)
bucket_elems = tree.findall(".//span[@class='repo-name']/")
bucket_names = [bucket.text_content.replace("n", "").strip() for bucket in bucket_elems]
print bucket_names
1
2
3
4
5
tree = html.fromstring(result.content)
bucket_elems = tree.findall(".//span[@class='repo-name']/")
bucket_names = [bucket.text_content.replace("n", "").strip() for bucket in bucket_elems]
print bucket_names
你也可以通過檢查從每個請求返回的狀態代碼來驗證這些請求結果。它不會總是能讓你知道登錄階段是否是成功的,但是可以用來作為一個驗證指標。
例如:
Python
result.ok # 會告訴我們最後一次請求是否成功
result.status_code # 會返回給我們最後一次請求的狀態
1
2
result.ok # 會告訴我們最後一次請求是否成功
result.status_code # 會返回給我們最後一次請求的狀態
就是這樣。
⑻ 如何使用python爬取知乎數據並做簡單分析
一、使用的技術棧:
爬蟲:python27 +requests+json+bs4+time
分析工具: ELK套件
開發工具:pycharm
數據成果簡單的可視化分析
1.性別分布
0 綠色代表的是男性 ^ . ^
1 代表的是女性
-1 性別不確定
可見知乎的用戶男性頗多。
二、粉絲最多的top30
粉絲最多的前三十名:依次是張佳瑋、李開復、黃繼新等等,去知乎上查這些人,也差不多這個排名,說明爬取的數據具有一定的說服力。
三、寫文章最多的top30
四、爬蟲架構
爬蟲架構圖如下:
說明:
選擇一個活躍的用戶(比如李開復)的url作為入口url.並將已爬取的url存在set中。
抓取內容,並解析該用戶的關注的用戶的列表url,添加這些url到另一個set中,並用已爬取的url作為過濾。
解析該用戶的個人信息,並存取到本地磁碟。
logstash取實時的獲取本地磁碟的用戶數據,並給elsticsearchkibana和elasticsearch配合,將數據轉換成用戶友好的可視化圖形。
五、編碼
爬取一個url:
解析內容:
存本地文件:
代碼說明:
* 需要修改獲取requests請求頭的authorization。
* 需要修改你的文件存儲路徑。
源碼下載:點擊這里,記得star哦!https : // github . com/forezp/ZhihuSpiderMan六、如何獲取authorization
打開chorme,打開https : // www. hu .com/,
登陸,首頁隨便找個用戶,進入他的個人主頁,F12(或滑鼠右鍵,點檢查)七、可改進的地方
可增加線程池,提高爬蟲效率
存儲url的時候我才用的set(),並且採用緩存策略,最多隻存2000個url,防止內存不夠,其實可以存在redis中。
存儲爬取後的用戶我說採取的是本地文件的方式,更好的方式應該是存在mongodb中。
對爬取的用戶應該有一個信息的過濾,比如用戶的粉絲數需要大與100或者參與話題數大於10等才存儲。防止抓取了過多的僵屍用戶。
八、關於ELK套件
關於elk的套件安裝就不討論了,具體見官網就行了。網站:https : // www . elastic . co/另外logstash的配置文件如下:
從爬取的用戶數據可分析的地方很多,比如地域、學歷、年齡等等,我就不一一列舉了。另外,我覺得爬蟲是一件非常有意思的事情,在這個內容消費升級的年代,如何在廣闊的互聯網的數據海洋中挖掘有價值的數據,是一件值得思考和需不斷踐行的事情。
⑼ python怎麼爬取某個人的微信朋友圈的信息
主要思路
從UI獲取文本信息是最為簡單的方法,於是應該優先逆向UI代碼部分。
逆向微信apk
首先解包微信apk,用dex2jar反編譯classes.dex,然後用JD-GUI查看jar源碼。當然,能看到的源碼都是經過高度混淆的。但是,繼承自安卓重要組件(如Activity、Service等)的類名無法被混淆,於是還是能從中看到點東西。
首先定位到微信APP package。我們知道這個是 com.tencent.mm。
在 com.tencent.mm
中,我們找到一個 ui
包,有點意思。
展開 com.tencent.mm.ui
,發現多個未被混淆的類,其中發現 MMBaseActivity直接繼承自 Activity
, MMFragmentActivity
繼承自 ActionBarActivity
, MMActivity
繼承自 MMFragmentActivity
,並且 MMActivity
是微信中大多數Activity的父類:
public class MMFragmentActivity
extends ActionBarActivity
implements SwipeBackLayout.a, b.a {
...
}
public abstract class MMActivity
extends MMFragmentActivity {
...
}
public class MMBaseActivity
extends Activity {
...
}
現在需要找出朋友圈的Activity,為此要用Xposed hook MMActivity。
創建一個Xposed模塊
參考 [TUTORIAL]Xposed mole devlopment,創建一個Xposed項目。
簡單Xposed模塊的基本思想是:hook某個APP中的某個方法,從而達到讀寫數據的目的。
小編嘗試hook com.tencent.mm.ui.MMActivity.setContentView這個方法,並列印出這個Activity下的全部TextView內容。那麼首先需要遍歷這個Activity下的所有TextView,遍歷ViewGroup的方法參考了SO的以下代碼:
private void getAllTextViews(final View v) {if (v instanceof ViewGroup) {
ViewGroup vg = (ViewGroup) v;
for (int i = 0; i < vg.getChildCount(); i++) {View child = vg.getChildAt(i);
getAllTextViews(child);
}
} else if (v instanceof TextView ) {
dealWithTextView((TextView)v); //dealWithTextView(TextView tv)方法:列印TextView中的顯示文本}
}
Hook MMActivity.setContentView
的關鍵代碼如下:
findAndHookMethod("com.tencent.mm.ui.MMActivity", lpparam.classLoader, "setContentView", View.class, new XC_MethodHook() {...
});
在findAndHookMethod方法中,第一個參數為完整類名,第三個參數為需要hook的方法名,其後若干個參數分別對應該方法的各形參類型。在這里, Activity.setContentView(View view)方法只有一個類型為 View
的形參,因此傳入一個 View.class
。
現在,期望的結果是運行時可以從Log中讀取到每個Activity中的所有的TextView的顯示內容。
但是,因為View中的數據並不一定在 setContentView()時就載入完畢,因此小編的實驗結果是,log中啥都沒有。
意外的收獲
當切換到朋友圈頁面時,Xposed模塊報了一個異常,異常源從 com.tencent.mm.plugin.sns.ui.SnsTimeLineUI這個類捕捉到。從類名上看,這個很有可能是朋友圈首頁的UI類。展開這個類,發現更多有趣的東西:
這個類下有個子類 a
(被混淆過的類名),該子類下有個名為 gyO的 ListView
類的實例。我們知道, ListView
是顯示列表類的UI組件,有可能就是用來展示朋友圈的列表。
順藤摸瓜
那麼,我們先要獲得一個 SnsTimeLineUI.a.gyO的實例。但是在這之前,要先獲得一個 com.tencent.mm.plugin.sns.ui.SnsTimeLineUI.a的實例。繼續搜索,發現 com.tencent.mm.plugin.sns.ui.SnsTimeLineUI有一個名為 gLZ
的 SnsTimeLineUI.a
實例,那麼我們先取得這個實例。
經過測試, com.tencent.mm.plugin.sns.ui.SnsTimeLineUI.a(boolean, boolean, String, boolean)這個方法在每次初始化微信界面的時候都會被調用。因此我們將hook這個方法,並從中取得 gLZ。
findAndHookMethod("com.tencent.mm.plugin.sns.ui.SnsTimeLineUI", lpparam.classLoader, "a", boolean.class, boolean.class, String.class, boolean.class, new XC_MethodHook() {@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {XposedBridge.log("Hooked. ");
Object currentObject = param.thisObject;
for (Field field : currentObject.getClass().getDeclaredFields()) { //遍歷類成員field.setAccessible(true);
Object value = field.get(currentObject);
if (field.getName().equals("gLZ")) {
XposedBridge.log("Child A found.");
childA = value;
//這里獲得了gLZ
...
}
}
}
});
現在取得了 SnsTimeLineUI.a
的一個實例 gLZ
,需要取得這個類下的 ListView
類型的 gyO
屬性。
private void dealWithA() throws Throwable{if (childA == null) {
return;
}
for (Field field : childA.getClass().getDeclaredFields()) { //遍歷屬性field.setAccessible(true);
Object value = field.get(childA);
if (field.getName().equals("gyO")) { //取得了gyOViewGroup vg = (ListView)value;
for (int i = 0; i < vg.getChildCount(); i++) { //遍歷這個ListView的每一個子View...
View child = vg.getChildAt(i);
getAllTextViews(child); //這里調用上文的getAllTextViews()方法,每一個子View里的所有TextView的文本...
}
}
}
}
現在已經可以將朋友圈頁面中的全部文字信息列印出來了。我們需要根據TextView的子類名判斷這些文字是朋友圈內容、好友昵稱、點贊或評論等。
private void dealWithTextView(TextView v) {String className = v.getClass().getName();String text = ((TextView)v).getText().toString().trim().replaceAll("\n", " ");if (!v.isShown())
return;
if (text.equals(""))
return;
if (className.equals("com.tencent.mm.plugin.sns.ui.AsyncTextView")) {//好友昵稱
...
}
else if (className.equals("com.tencent.mm.plugin.sns.ui.SnsTextView")) {//朋友圈文字內容
...
}
else if (className.equals("com.tencent.mm.plugin.sns.ui.MaskTextView")) {if (!text.contains(":")) {
//點贊
...
} else {
//評論
...
}
}
}
自此,我們已經從微信APP里取得了朋友圈數據。當然,這部分抓取代碼需要定時執行。因為從 ListView中抓到的數據只有當前顯示在屏幕上的可見部分,為此需要每隔很短一段時間再次執行,讓用戶在下滑載入的過程中抓取更多數據。
剩下的就是數據分類處理和格式化輸出到文件,受本文篇幅所限不再贅述,詳細實現可參考作者GitHub上的源碼。
⑽ 如何一個月入門Python爬蟲,輕松爬取大規模數據
鏈接:https://pan..com/s/1wMgTx-M-Ea9y1IYn-UTZaA
課程簡介
畢業不知如何就業?工作效率低經常挨罵?很多次想學編程都沒有學會?
Python 實戰:四周實現爬蟲系統,無需編程基礎,二十八天掌握一項謀生技能。
帶你學到如何從網上批量獲得幾十萬數據,如何處理海量大數據,數據可視化及網站製作。
課程目錄
開始之前,魔力手冊 for 實戰學員預習
第一周:學會爬取網頁信息
第二周:學會爬取大規模數據
第三周:數據統計與分析
第四周:搭建 Django 數據可視化網站
......