【发布时间】:2018-01-14 07:02:39
【问题描述】:
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)
大家好。我一直想抓取一些数据,当我注意到打印输出将 (') 替换为 (â\x80\x99) 时,我几乎完成了我的抓取。例如,包含“China's”的标题是“Chinaâ\x80\x99s”。我做了一些研究并尝试使用解码/编码(utf-8)但无济于事。它只会告诉我你不能在 str() 上运行解码。我尝试使用 re.sub() 可以让我删除 (â\x80\x99) 但不会让我用 (') 替换它因为我想使用自然语言处理来解释数据担心没有撇号将大大改变含义。非常感谢您的帮助,我觉得我遇到了这个问题。
【问题讨论】: