【问题标题】:Problems crawling wordreference抓取单词参考的问题
【发布时间】:2016-04-23 23:31:24
【问题描述】:

我正在尝试爬取wordreference,但没有成功。

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

例如,我想提取给定单词的前两个含义,所以在这个 url:http://www.wordreference.com/es/translation.asp?tranword=crane 我需要提取 grullagrú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 以一种优雅的方式来做。

非常感谢

【问题讨论】:

    标签: python xpath web-scraping web-crawler lxml


    【解决方案1】:

    您似乎需要发送User-Agent 标头,请参阅Changing user agent on urllib2.urlopen

    另外,只需切换到requests 就可以了(默认情况下它会自动发送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)
    

    打印:

    grulla 
    grúa 
    plataforma 
    ...
    grulla blanca 
    grulla trompetera 
    

    【讨论】:

    • 谢谢,但是,它不能与 User Agent urllib 一起使用的原因是什么。我已经爬过其他网站,一个没有问题,为什么不是这个?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-03
    • 2011-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多