-2
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)
这个python代码是为了刮去工作城市列表(他们的'a href'标签)并将其存储在列表l1中。但在这里我得到一个空白列表。 Chrome浏览器控制台使用相同的xpath,但它不适用于此代码。由于我添加的报头,使我的代码充当浏览器,但它仍然不工作..为什么使用请求包的这个python web scraping代码不工作?
http://i.stack.imgur.com/Xx1xW.jpg
你的代码的哪部分不工作?如果您在代码的末尾添加'print l1',则会显示您的列表中已填入URL ... – Mangohero1
嗨德鲁。我不明白。对我来说,当我在Jupyter Qtconsole中运行代码时,它会返回一个空白列表! –
那真奇怪。尽管我对Jupyter QtConsole并不熟悉,但这可能与它有关。 – Mangohero1