-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