urllib2.urlopen(url).read()无法读取URL内容

时间:2015-12-24 06:30:36

标签: python web web-scraping

我正在尝试使用以下python命令阅读链接的网页内容:http://www.quikr.com/Mobile-Phones/y149

import requests
import urllib2
hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11'}
url = 'http://www.quikr.com/Mobile-Phones/y149'
req = urllib2.Request(url, headers=hdr)
page = urllib2.urlopen(req).read()

print page给出以下输出:

<!DOCTYPE html>
<head>
<META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="refresh" content="10; url=/distil_r_captcha.html?Ref=/Mobile-Phones/y149&amp;distil_RID=97C53AFC-AA02-11E5-B76A-8C12C4D2AB6C&amp;distil_TID=20151224055301" />
<script type="text/javascript">
    (function(window){
        try {
            if (typeof sessionStorage !== 'undefined'){
                sessionStorage.setItem('distil_referrer', document.referrer);
            }
        } catch (e){}
    })(window);
</script>
<script type="text/javascript" src="/QkrDIV1cexsvzwdadarecara.js" defer></script><style type="text/css">#d__fFH{position:absolute;top:-5000px;left:-5000px}#d__fF{font-family:serif;font-size:200px;visibility:hidden}#qttwcrxueetv{display:none!important}</style></head>
<body>
<div id="distil_ident_block">&nbsp;</div>
</body>
</html>

是否有任何解决方法可以获取实际的网址内容。任何帮助表示赞赏。 在此先感谢!!

1 个答案:

答案 0 :(得分:1)

一种选择是通过selenium自动化真实的浏览器。工作样本:

from selenium import webdriver

driver = webdriver.Firefox()
driver.get("http://www.quikr.com/Mobile-Phones/y149")

for phone in driver.find_elements_by_css_selector(".snb_entire_ad"):
    link = phone.find_element_by_css_selector("a.adttllnk")

    print link.text

driver.close()

如果您想获取页面源,请使用.page_source(当然关闭驱动程序之前):

print(driver.page_source)