爬行wordreference时出现问题

2024-06-12 08:19:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图抓取wordreference,但我没有成功。在

我遇到的第一个问题是,很大一部分是通过JavaScript加载的,但这应该不是什么大问题,因为我可以在源代码中看到我需要什么。在

例如,我想提取给定单词的前两个意思,所以在这个url中:http://www.wordreference.com/es/translation.asp?tranword=crane我需要提取grulla和{}。在

这是我的代码:

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

结果是我得到了一个空列表。在

我也试着用刮屑爬过去,但没有成功。我不确定是怎么回事,我能抓取它的唯一方法是使用curl,但这是慢操作,我想用一种优雅的方式,使用Python。在

非常感谢


Tags: importcomhttpurltransdoceswww
1条回答
网友
1楼 · 发布于 2024-06-12 08:19:39

看起来您需要发送一个User-Agent头,请参见Changing user agent on urllib2.urlopen。在

另外,只需切换到^{}就可以了(默认情况下,它会自动发送python-requests/version用户代理):

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)

印刷品:

^{pr2}$

相关问题 更多 >