我想開始使用lxml解析html。我知道從基本xpath /
應該選擇根節點,//body
應該選擇身體元素節點,無論它在dom中,無論它在哪裏,但是我得到一個空列表的所有。lxml:解析html,無法獲取節點
from lxml import html
import urllib2
headers = {'User-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:24.0) Gecko/20100101 Firefox/24.0'}
req = urllib2.Request("http://news.ycombinator.com", None, headers)
r = urllib2.urlopen(req).read()
x = html.fromstring(r)
x.xpath("/")
[]
編輯:
例如,下面是該頁面的另一個有效的XPath表達式返回一個空列表
x.xpath("/html/body/center/table/tbody/tr[3]/td/table/tbody/tr[1]/td[3]")
[]
# when it should have returned the following (as of this time)
# <td class="title"><a href="http://www.tomdalling.com/blog/modern-opengl/opengl-in-2014/">OpenGL in 2014</a><span class="comhead"> (tomdalling.com) </span></td>
難道你沒有得到這個** urllib2.HTTPError:HTTP錯誤403:禁止** – Nabin 2014-09-21 10:29:04
** [] **做什麼? – Nabin 2014-09-21 10:29:24
@Nabin哦,在實際的代碼中,我使用了一個代理和一個假的用戶代理,我沒有發佈。 '[]'是最後一行的輸出。我會讓這個代碼可行,只需一分鐘。 – yayu 2014-09-21 10:30:55