時間:2023-07-04 05:39:01 | 來源:網(wǎng)站運營
時間:2023-07-04 05:39:01 來源:網(wǎng)站運營
寫爬蟲時如何解決網(wǎng)頁亂碼問題:實戰(zhàn)講解,文章較長,對爬蟲比較熟悉的瀏覽翻看章節(jié) 2.3 獲取新聞文本內(nèi)容。http://top.baidu.com/buzz?b=1
#百度風云榜頁面網(wǎng)址(含有50個熱門新聞的關(guān)鍵詞)fengyunbang_url = 'http://top.baidu.com/buzz?b=1'resp = requests.get(fengyunbang_url)#從html文件中解析出 事件字段和 網(wǎng)址字段doc = PyQuery(resp.text)for item in doc.items('.keyword'): keyword = item('a').text().split(' ')[0] keyword_link=item('a').attr.href print(keyword,keyword_link)
運行,結(jié)果keyword全部為亂碼,沒有一點中文的痕跡。 def get_keywords_news_links(keyword_link): """ 訪問關(guān)鍵詞百度網(wǎng)址,得到相關(guān)新聞的link :param keyword_link: :return: """ headers = {'User-Agent': '你的user-agent'} resp = requests.get(keyword_link, headers=headers) bsObj = BeautifulSoup(resp.text, 'html.parser') news_items = bsObj.find_all('div', {'class': 'result c-container '}) news_links = [] for item in news_items: links = re.findall('href="(.*?)"', str(item)) news_links.extend(links) #防止鏈接重復 news_links = set(news_links) return news_links
但是后來發(fā)現(xiàn)有的鏈接是無法訪問的,比如運行中居然抽取出含有http://cache.baiducontent***
這種的網(wǎng)頁,經(jīng)過測試,只要剔除掉這種鏈接,剩下的都為有效鏈接。 def get_news_content(link): """ 根據(jù)新聞網(wǎng)址,獲取新聞數(shù)據(jù) :return: 新聞內(nèi)容 """ resp = requests.get(link) #最終只有漢字保留。 news_text = ''.join(re.findall('[/u4e00-/u9fa5]+', resp.text)) return news_text
但是運行過程中,經(jīng)常返回空。說明正則匹配中文時候匹配不到。很可能的原因是頁面中沒有中文,但是我們檢測了這些頁面都是有中文的,那么很有可能是因為頁面亂碼,導致正則[/u4e00-/u9fa5]+
無法匹配到中文。經(jīng)過檢測,真的是亂碼。解決辦法resp.encoding='編碼'
。但是編碼
是什么值呢?這里我用新的方法,chardect庫檢測二進制數(shù)據(jù)中采用的編碼方式。def get_news_content(link): """ 根據(jù)新聞網(wǎng)址,獲取新聞數(shù)據(jù) :return: 新聞內(nèi)容 """ resp = requests.get(link) news_text = ''.join(re.findall('[/u4e00-/u9fa5]+', resp.text)) #網(wǎng)頁亂碼,導致news_text為空 if not news_text: #根據(jù)二進制數(shù)據(jù)檢測html的編碼。 #resp.content獲取html二進制數(shù)據(jù) chaset = chardet.detect(resp.content)['encoding'] #解決編碼問題 resp.encoding = chaset news_text = ''.join(re.findall('[/u4e00-/u9fa5]+', resp.text)) return news_text return news_text
#主函數(shù),訪問并保存所有的新聞數(shù)據(jù)def FetchAndSave(): #百度風云榜頁面網(wǎng)址(含有50個熱門新聞的關(guān)鍵詞) fengyunbang_url = 'http://top.baidu.com/buzz?b=1' resp=requests.get(fengyunbang_url) resp.encoding='gb2312' #新建excel文件保存數(shù)據(jù)。 csvf = open('data.csv', 'a+', encoding='gbk', newline='') writer = csv.writer(csvf) writer.writerow(('news_content', 'keyword')) #從heml文件中解析出 事件字段和 網(wǎng)址字段 doc = PyQuery(resp.text) for itm in doc.items('.keyword'): keyword = itm('a').text().split(' ')[0] keyword_link = itm('a').attr.href news_links = get_keywords_news_links(keyword_link) for news_link in news_links: try: content = get_news_content(news_link) #防止新聞內(nèi)容為空的寫入csv中 if content: writer.writerow((content, keyword)) except: print(news_link)#運行爬蟲FetchAndSave()
關(guān)鍵詞:解決,爬蟲
微信公眾號
版權(quán)所有? 億企邦 1997-2025 保留一切法律許可權(quán)利。