import requests
from bs4 import BeautifulSoup
import re
source_url = requests.get('http://www.nytimes.com/pages/business/index.html')
div_classes = {'class' :['ledeStory' , 'story']}
title_tags = ['h2','h3','h4','h5','h6']
source_text = source_url.text
soup = BeautifulSoup(source_text, 'html.parser')
stories = soup.find_all("div", div_classes)
h = []; h2 = []; h3 = []; h4 =[]
for x in range(len(stories)):
for x2 in range(len(title_tags)):
hold = []; hold2 = []
hold = stories[x].find(title_tags[x2])
if hold is not None:
hold2 = hold.find('a')
if hold2 is not None:
hh = (((hold.text.strip('a'))).strip())
h.append(hh)
#h.append(re.sub(r'[^\x00-\x7f]',r'', ((hold.text.strip('a'))).strip()))
#h2.append(hold2.get('href'))
hold = []
hold = stories[x].find('p')
if hold is not None:
h3.append(re.sub(r'[^\x00-\x7f]',r'',((hold.text.strip('p')).strip())))
else:
h3.append('None')
h4.append(h)
h4.append(h2)
h4.append(h3)
print(h4)
嘿大家打印出來。我一直想刮一些數據,當我注意到打印輸出正在用(×80 \ x99)替換(')時,我幾乎完成了刮刀。例如,包含「中國」的標題即將出現「中國×××××××」。我做了一些研究,並嘗試使用解碼/編碼(utf-8)無濟於事。它只會告訴我,你不能在str()上運行解碼。我嘗試過使用re.sub(),它可以讓我刪除('x80 \ x99),但不會讓我用(')替換它因爲我想用自然語言處理來解釋數據,所以沒有撇號將極大地改變意義。幫助將不勝感激,我覺得我已經與這一塊一塊。撇號爲A X80 X99
代碼示例的最後一行暗示它是Python 3.x –
@CoryMadden:是的,你是對的。所以選項3可能(幾乎肯定)不相關。 –
哎呀,我誤解了所有這些標準是問題所在。 –