【发布时间】:2017-04-07 23:50:27
【问题描述】:
我用 urllib 编写了一个程序,它从网页(在本例中为 nytimes.com)获取所有文章标题。只有一个问题。有些标题有分号,如果打印出来,会导致难看的“There\xe2\x80\x99s”。所以我尝试用 ' 替换 \xe2\x80\x99 但它似乎不起作用。我认为元组有问题。不幸的是,我无法创建元组,这会导致同样的问题。
import urllib.request
import urllib.parse
import re
url = 'https://www.nytimes.com/'
headers = {}
headers['User-Agent'] = 'Mozilla/5.0 (X11; Linux i686)'
req = urllib.request.Request(url, headers = headers)
resp = urllib.request.urlopen(req)
resp_data = resp.read()
par = re.findall(r'story-heading"><a href="(.*?)">(.*?)</a>',str(resp_data))
for n in par:
print(n[1])
print(n[1].replace("\xe2\x80\x99","'"))
我尝试从元组创建字符串变量,但没有任何效果。我知道 BeautifulSoup 有另一种解决方案,但我想我会尝试找到自己的方式。
【问题讨论】:
标签: python python-3.x urllib