2017-08-23 32 views
1

我已經在python中編寫了一些代碼來從網頁中獲取公司的詳細信息和名稱。我在腳本中使用了css選擇器來收集這些項目。然而,當我運行它時,我只能得到「公司詳細信息」和「聯繫」,而只有第一部分用「br」標記分隔出完整的字符串。我怎麼能得到除了我所擁有的全部部分?在Python腳本中使用選擇器來抓取項目

腳本我試圖用:

import requests ; from lxml import html 

tree = html.fromstring(requests.get("https://www.austrade.gov.au/SupplierDetails.aspx?ORGID=ORG8000000314&folderid=1736").text) 
for title in tree.cssselect("div.contact-details"): 
    cDetails = title.cssselect("h3:contains('Contact Details')+p")[0].text 
    cContact = title.cssselect("h4:contains('Contact')+p")[0].text 
    print(cDetails, cContact) 

元素在其中搜索結果是:

<div class="contact-details block dark"> 
       <h3>Contact Details</h3><p>Company Name: Distance Learning Australia Pty Ltd<br>Phone: +61 2 6262 2964<br>Fax: +61 2 6169 3168<br>Email: <a href="mailto:[email protected]">[email protected]</a><br>Web: <a target="_blank" href="http://dla.edu.au">http://dla.edu.au</a></p><h4>Address</h4><p>Suite 108A, 49 Phillip Avenue<br>Watson<br>ACT<br>2602</p><h4>Contact</h4><p>Name: Christine Jarrett<br>Phone: +61 2 6262 2964<br>Fax: +61 2 6169 3168<br>Email: <a href="mailto:[email protected]">[email protected]</a></p> 
      </div> 

結果我得到:

Company Name: Distance Learning Australia Pty Ltd Name: Christine Jarrett 

結果我之後:

Company Name: Distance Learning Australia Pty Ltd 
Phone: +61 2 6262 2964 
Fax: +61 2 6169 3168 
Email: [email protected] 

Name: Christine Jarrett 
Phone: +61 2 6262 2964 
Fax: +61 2 6169 3168 
Email: [email protected] 

順便說一句,我的意圖是使用選擇器而不是xpath執行上述操作。提前致謝。

回答

1

只需使用如下方法text_content()更換text屬性來獲取所需的輸出:

cDetails = title.cssselect("h3:contains('Contact Details')+p")[0].text_content() 
cContact = title.cssselect("h4:contains('Contact')+p")[0].text_content() 
+0

當有安德森,有希望!非常感謝先生。它做了魔術。 – SIM

+0

在此背景之外要了解的一件事,先生安德森先生。爲什麼在我的選擇器原因中不能使用「:: after」或「:: before」如果我試圖做任何事情,我會得到一個錯誤「不支持僞元素。」不過,我在一個關於css選擇器的文檔中發現了這個。是否有任何版本相關的衝突? – SIM

+1

您不能找到僞元素,因爲它們不是DOM的一部分。可以在CSS選擇器中使用它們來設置HTML源代碼中的某些樣式,但不適用於網頁抓取 – Andersson

1

text最先返回文本節點。如果要在抓文本節點使用xpath像遍歷所有子節點:

company_details = title.cssselect("h3:contains('Contact Details')+p")[0] 
for node in company_details.xpath("child::node()"): 
    print node 

結果:

Company Name: Distance Learning Australia Pty Ltd 
<Element br at 0x7f625419eaa0> 
Phone: +61 2 6262 2964 
<Element br at 0x7f625419ed08> 
Fax: +61 2 6169 3168 
<Element br at 0x7f625419e940> 
Email: 
<Element a at 0x7f625419e8e8> 
<Element br at 0x7f625419eba8> 
Web: 
<Element a at 0x7f6254155af8> 
相關問題