Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么这个使用requests包的pythonweb抓取代码不起作用?_Python_Python 2.7_Web Scraping_Python Requests - Fatal编程技术网

为什么这个使用requests包的pythonweb抓取代码不起作用?

为什么这个使用requests包的pythonweb抓取代码不起作用?,python,python-2.7,web-scraping,python-requests,Python,Python 2.7,Web Scraping,Python Requests,这段python代码旨在刮取作业citiestheir'a href'标记的列表,并将其存储在列表l1中。但在这里我得到了一张空白名单。相同的xpath在Chrome控制台上工作,但在这段代码中不起作用。因此,我添加了标题,使我的代码充当浏览器,但它仍然不起作用 我尝试使用SeleniumWebDriver实现同样的功能,这也成功了。当您的计算机成功执行此操作时,所使用的某个库中可能会出现问题 import lxml.html import requests l1=[] header

这段python代码旨在刮取作业citiestheir'a href'标记的列表,并将其存储在列表l1中。但在这里我得到了一张空白名单。相同的xpath在Chrome控制台上工作,但在这段代码中不起作用。因此,我添加了标题,使我的代码充当浏览器,但它仍然不起作用


我尝试使用SeleniumWebDriver实现同样的功能,这也成功了。当您的计算机成功执行此操作时,所使用的某个库中可能会出现问题

import lxml.html  
import requests  
l1=[]  
headers= {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'}  
r = requests.get('http://www.naukri.com/jobs-by-location', headers=headers)    
html = r.content  
root = lxml.html.fromstring(html)  
urls = root.xpath('//div[4]/div/div[1]/div/a/@href') #This xpath should give the list of cities(their links)  
l1.extend(urls)     

您的代码的哪一部分不起作用?如果在代码末尾添加打印l1,则表明列表中填充了URL…您好。我不明白。对我来说,当我在Jupyter Qtconsole中运行代码时,它返回一个空白列表!那真奇怪。虽然我不熟悉Jupyter QtConsole,但这可能与它有关。它也不在Spyder editor中执行。我使用的是Windows 8.1操作系统,并且安装了anaconda for python 2.7。您的代码工作正常,因此显然有一些特定于您运行代码的方式,您是否查看了源请求返回?
import selenium.webdriver as driver

browser = driver.Chrome()
browser.get("http://www.naukri.com/jobs-by-location")
links = browser.find_elements_by_xpath("//div[4]/div/div[1]/div/a")
for link in links:
    href = link.get_attribute("href")
    print(href)
browser.quit()