因此我對此很陌生,在這個問題上,我一直沒能在google上找到任何東西。使用Python Request/lxml進行網頁抓取:從ul/li獲取數據
我使用要求和LXML與的Python,我已經看到有很多關於網頁抓取不同的模塊,但沒有任何理由在選擇一個另一個?你可以使用request/lxml來做同樣的事情嗎?例如BeautifulSoup?
無論如何,這裏是我的實際的問題;
這是我的代碼:
import requests
from lxml import html
# Login data
inputUrl = 'http://forum.mytestsite.com/login'
usr = 'myusername'
pwd = 'mypassword'
payload = dict(login=usr, password=pwd)
# Open session
with requests.Session() as s:
# Login
s.post(inputUrl, data=payload)
# Get page data
pageResult = s.get('http://forum.mytestsite.com/icons/', allow_redirects=False)
pageResult = html.fromstring(pageResult.content)
pageIcons = pageResult.xpath('//script[@id="table-icons"]/text()')
print pageIcons[0]
結果打印時pageIcons [0]:
<ul id="icons">
{{#each icons}}
<li data-handle="{{handle}}">
<img src="{{image_path}}" alt="{{desc_or_name this}}" title="{{desc_or_name this}}">
</li>
{{/each}}
</ul>
這是生成的網站/ js代碼圖標:
<script id="table-icons" type="text/x-handlebars-template">
<ul id="icons">
{{#each icons}}
<li data-handle="{{handle}}">
<img src="{{image_path}}" alt="{{desc_or_name this}}" title="{{desc_or_name this}}">
</li>
{{/each}}
</ul>
</script>
而這裏的頁面上的結果:
<ul id="icons">
<li data-handle="558FSTBI" class="">
<img src="http://testsite.com/icons/558FSTBI.1.png" alt="Icon 1" title="Icon 1">
</li>
<li data-handle="310AYTZI">
<img src="http://testsite.com/icons/310AYTZI.1.png" alt="Icon 2" title="Icon 2">
</li>
<li data-handle="669PQXBI" class="">
<img src="http://testsite.com/icons/669PQXBI.1.png" alt="Icon 3" title="Icon 3">
</li>
</ul>
我的目標:
我想要做的是檢索所有的li data手柄,但我一直無法弄清楚如何檢索這些數據。所以我的目標是檢索所有的圖標路徑和他們的頭銜,有誰能幫我解決這個問題嗎?我真的很感激任何幫助:)
'// script'不是呈現的HTML的一部分。你爲什麼試圖解析模板代碼? –
嗯,因爲我是一個noob:P我是因爲腳本的結果給了我實際上想要的ul/li句柄,所以這樣做是合乎邏輯的。我的意思是,渲染的HTML是從腳本生成的,對吧?我還能如何獲得鏈接? – Lorena
您無法從python請求獲取模板代碼。另外,如果它在頁面加載後呈現,那麼您會得到一個空列表,並且無論如何您都不能使用請求。 https://stackoverflow.com/questions/13960567/reading-dynamically-generated-web-pages-using-python –