2017-03-20 57 views
1

在python3中使用chrome和xpath,我嘗試提取「href」屬性on this web page的值。的「href」屬性包含(法語「BANDE-annonce」)鏈接到電影的預告片,我感興趣的使用xpath(python3)href屬性爲空

Here is the html of the page, with the href I want in the <a> tag (highlighted in blue)

第一件事,使用XPath,它出現了「一個」標籤是「span」標籤。事實上,使用此代碼:

response_main=urllib.request.urlopen("http://www.allocine.fr/film/fichefilm_gen_cfilm=231874.html") 
htmlparser = etree.HTMLParser() 
tree_main = etree.parse(response_main, htmlparser) 
tree_main.xpath('//*[@id=\"content-start\"]/article/section[3]/div[2]/div/div/div/div[1]/*') 

我得到這樣的結果:

[<Element span at 0x111f70c08>] 

所以「格」標籤不包含「一」的標籤,但只是一個「跨度」標籤。我讀過瀏覽器中的html可視化並不總是反映服務器發送的「真實」html。因此,我試圖用這個命令提取HREF:

response_main=urllib.request.urlopen("http://www.allocine.fr/film/fichefilm_gen_cfilm=231874.html") 
htmlparser = etree.HTMLParser() 
tree_main = etree.parse(response_main, htmlparser) 
tree_main.xpath('//*[@id=\"content-start\"]/article/section[3]/div[2]/div/div/div/div[1]/span/@href') 

不幸的是,這個沒有返回值...當我檢查「跨度」標籤中的屬性與此命令:

tree_main.xpath('//*[@id=\"content-start\"]/article/section[3]/div[2]/div/div/div/div[1]/span/@*') 

我得到了「class」屬性的有關的「href」的值,但沒有...:

['ACrL3ZACrpZGVvL3BsYXllcl9nZW5fY21lZGlhPTE5NTYwMDcyJmNmaWxtPTIzMTg3NC5odG1s meta-title-link'] 

我想一些幫助,瞭解這裏發生了什麼。爲什麼「a」標籤是「span」標籤?而對我來說最重要的問題是,我如何提取「href」屬性的值?

非常感謝您的幫助!

回答

2

JavaScript動態生成的必需鏈接。用urllib.request您只能獲得初始HTML頁面源,而您需要HTML之後全部JavaScript已執行。

您可以使用selenium + chromedriver獲得動態生成的內容:

from selenium import webdriver as web 
from selenium.webdriver.common.by import By 
from selenium.webdriver.support import expected_conditions as EC 
from selenium.webdriver.support.ui import WebDriverWait as wait 

driver = web.Chrome("/path/to/chromedriver") 
driver.get("http://www.allocine.fr/film/fichefilm_gen_cfilm=231874.html") 
link = wait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//div[@class='meta-title']/a[@class='xXx meta-title-link']"))) 
print(link.get_attribute('href')) 
+0

感謝@Andersson我使用蟒蛇和Spyder在python3的代碼提示。所以我給Anaconda添加了硒3.3.1和chromedriver 2.24.1。 – user1671537

+0

它爲你工作還是有一些問題? – Andersson

+0

最後一個問題!每當我使用這個命令:drive = web.chrome(),就會打開一個chrome瀏覽器。您是否知道在打印完href後關閉它的方法? (肯定有命令行) 如果多次使用此命令,恐怕可能會出現問題:) – user1671537