在 python 中使用 xpath 从网站进行数据挖掘

data mining from website using xpath in python

我运行这个程序但是它只给我“[]”而不是给网页data.please帮助

import urllib 
   import re
   import lxml.html

   start_link= "http://aepcindia.com/ApparelMarketplaces/detail"
   html_string = urllib.urlopen(start_link)
   dom =  lxml.html.fromstring(html_string.read())
   side_bar_link = dom.xpath("//*[@id='show_cont']/div/table/tr[2]/td[2]/text()")
   print side_bar_link 
   file = open("next_page.txt","w")
   for link in side_bar_link:
       file.write(link)
       print link

   file.close()

您正在下载的 HTML 源包含一个空白内容区域:<div id="show_cont"></div>。此 div 稍后由 javascript 函数 showData() 填充。当您在浏览器中查看该页面时,javascript 之前已执行,而您仅使用 urllib 下载 HTML 源时并非如此。

要获取您想要的数据,您可以尝试在 showData() 函数中模仿 POST 请求,或者最好使用 scriptable 无头浏览器来抓取网站。

更新: 虽然无头浏览器是一种更普遍适用的方法,但在这种情况下,它可能会产生开销。实际上,对 showData() 函数进行逆向工程会更好。其中的 alax-call 太明显了,提供了一个简单的 HTML table 并且您还可以限制搜索 :) http://aepcindia.com/ApparelMarketplaces/ajax_detail/search_type:/search_value: