經過一晚上的BUG作戰(zhàn)椭懊,燒香之后,目前好像大功告成撩银,先上圖
只爬了24頁
代碼重寫了刑枝,之前的錯誤出現在18頁和23頁。BeautifulSoup本砰,解析之后碴裙,遇到 """,這個字符,導致無法定位需要的信息
三個"""点额,代碼解析出錯了舔株,所以重寫了
----JSON數據 obj=""" {"name":"Wes", "places_
首先感謝CSDN上面的各位大神的無私奉獻,每當不懂的時候还棱,百度出來的結果载慈,好多都是CSDN上面的博客幫我解決的,收集到的文章將用于學習pandas分析珍手。首先看搜索結果的鏈接
https://so.csdn.net/so/search/s.do?p=23&q=pandas&t=blog&domain=&o=&s=&u=&l=&f=&rbg=0办铡,p=23是頁數,q=pandas這是關鍵字琳要,t=blog寡具,就是搜索博客的意思,其他的沒有進行分析稚补,用這幾個就夠了童叠。
def get_wen_list(keyword, page):
rooturl = 'https://so.csdn.net/so/search/s.do?'
key = 'q=%s' % (keyword)
result_pool = []
for pnum in range(0, page):
search_url = rooturl + 'p=%d&' % (pnum) + key + '&t=blog&domain=&o=&s=&u=&l=&f=&rbg=0'
print('開始爬第%d頁鏈接' % pnum, search_url)
seget = requests.get(search_url)
Soup = BeautifulSoup(seget.text, 'lxml')
search_list = Soup.find_all(attrs={"class": "search-list-con"})
tilte_list = search_list.find_all(href=re.compile("https://blog.csdn.net"))
print() //以上的幾句是一開始用beautifuSoup,發(fā)現問題,后來直接用正則课幕,才有下面的語句
detail_list = re.findall('''/w+/article/details/[1-9][0-9]{7,}''', seget.text)
流程是:先按頁數get厦坛,博文的列表五垮,從中正則匹配出 作者的文章鏈接,文章鏈接如下
https://blog.csdn.net(這里不變) /chenzhenzhu2011/article/details/44183605 (要匹配的內容)
if detail_list: (獲得當頁所有的list后杜秸,因為有重復放仗,需要去重)
new_pool = []
new_pool = list(set(detail_list))
print(new_pool)
for detail_url in new_pool:
get_detail = requests.get("https://blog.csdn.net" + detail_url)
Soup = BeautifulSoup(get_detail.text, 'lxml')
title = Soup.find(attrs = {"class" : "title-article" }).get_text()
dtime = Soup.find(attrs = {"class" : "time"}).get_text()
browse = Soup.find(attrs = {"class" : "read-count"}).get_text()
author = detail_url.split("/", 2)
tmp = [author[1], title, dtime, browse, detail_url]
result_pool.append(tmp)
print(tmp)
獲得 ['作者' , '題目', '日期', '閱讀數', '鏈接'],返回列表,之后寫入CSV文件撬碟。
get_pool = get_wen_list(keyword, page)
copy_csv = open('pool.csv', 'a+', newline='')
fieldnames = ['atuhor', 'title', 'dtime', 'browse', 'liurl']
wr_pool = csv.writer(copy_csv)
wr_pool.writerow(fieldnames)
for pool in get_pool:
wr_pool.writerow(pool)
print("dWrite a total of %s bar data " % len(get_pool))
copy_csv.close()
下一步計劃爬文章的內容诞挨,學習下大神走過的路