我正在尝试抓取 wordreference,但没有成功。
我遇到的第一个问题是,很大一部分是通过 JavaScript 加载的,但这应该不是什么大问题,因为我可以在源代码中看到我需要的东西。
所以,例如,我想提取给定单词的前两个含义,所以在这个 url 中:http://www.wordreference.com/es/translation.asp?tranword=crane 我需要提取 grulla 和 grúa。
这是我的代码:
import lxml.html as lh
import urllib2
url = 'http://www.wordreference.com/es/translation.asp?tranword=crane'
doc = lh.parse((urllib2.urlopen(url)))
trans = doc.xpath('//td[@class="ToWrd"]/text()')
for i in trans:
print i
结果是我得到一个空列表。
我也试过用scrapy爬,没成功。我不确定发生了什么,我能够抓取它的唯一方法是使用 curl,但这太笨拙了,我想用 Python 以优雅的方式完成。
非常感谢
请您参考如下方法:
看起来您需要发送一个 User-Agent header ,请参阅 Changing user agent on urllib2.urlopen .
此外,只需切换到 requests可以解决这个问题(默认情况下它会自动发送 python-requests/version User Agent):
import lxml.html as lh
import requests
url = 'http://www.wordreference.com/es/translation.asp?tranword=crane'
response = requests.get("http://www.wordreference.com/es/translation.asp?tranword=crane")
doc = lh.fromstring(response.content)
trans = doc.xpath('//td[@class="ToWrd"]/text()')
for i in trans:
print(i)
打印:
grulla
grúa
plataforma
...
grulla blanca
grulla trompetera
