2017-08-07 70 views
1
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

回答

1

在ISO 8859-1和相關代碼集(其中有很多)中,â代碼點爲0xE2。當您將三個字節0xE2,0x80,0x99解釋爲UTF-8編碼時,字符爲U + 2019,右單引號(或',與'或'不同 - 您可能會也可能不會發現差異)。

我看到你的困難,這些都可能是你的麻煩的來源的任何一個或多個源的幾種可能性:

  1. 你的終端沒有設置來解釋UTF-8。
  2. 你的源代碼應該使用'(U + 0027,APOSTROPHE)。
  3. 您使用Python 2.x而不是Python 3.x,並且由於使用了Unicode(UTF-8)而出現問題。對此(如Cory Maddenpointed out),代碼以print(h4)即Python 3結尾,所以它可能不是問題。

將引號改爲ASCII撇號可能是最簡單的。另一方面,如果你從其他地方分析HTML,你可能不得不考慮你的腳本將如何處理UTF-8。使用Unicode U + 20xx範圍內的引號是非常普遍的選擇;也許你的刮刀需要處理它?

+0

代碼示例的最後一行暗示它是Python 3.x –

+1

@CoryMadden:是的,你是對的。所以選項3可能(幾乎肯定)不相關。 –

+1

哎呀,我誤解了所有這些標準是問題所在。 –