[英]scrape the value from a dropdown
我正在嘗試使用Python與Selenium和Beautiful Soup的組合從Web上的下拉列表元素中抓取值和文本。
我可以獲取文本,但無法通過get_attribute
命令獲取值。
當我打印位於網頁上的元素時,它將返回以下內容
得到它的打印語句給出錯誤:
None Type object is not callable
price=soup.find("select",{"id":"space-prices"})
print(price)
print(price.text)
print(price.get_attribute('value'))
print(price)的輸出是
<select class="pricing-bar-select" id="space-prices" name="space-prices"><option selected="selected" value="£360">Per Day</option>
<option value="£1,260">Per Week</option>
<option value="£5,460">Per Month</option>
<option value="£16,380">Per Quarter</option>
<option value="£65,520">Per Year</option></select>
該網頁的網址是
https://www.appearhere.co.uk/spaces/north-kensington-upcycling-store-and-cafe
嘗試這個:
from selenium import webdriver
from bs4 import BeautifulSoup
driver = webdriver.Chrome()
url= "https://www.appearhere.co.uk/spaces/north-kensington-upcycling-store-and-cafe"
driver.maximize_window()
driver.get(url)
content = driver.page_source.encode('utf-8').strip()
soup = BeautifulSoup(content,"html.parser")
price=soup.find("select",{"id":"space-prices"})
options = price.find_all("option")
options1=[y.text for y in options]
values = [o.get("value") for o in options]
for x in range(5):
print options1[x], values[x].encode('utf8')
driver.quit()
它將打印
Per Day £360
Per Week £1,260
Per Month £5,460
Per Quarter £16,380
Per Year £65,520
希望這就是你想要的
這是因為get_attribute
似乎為None
。 這不是prices
對象的有效屬性。 因此,這不是您可以調用的函數-因此會出現錯誤。 如果您prices.get_attribute
括號並僅打印prices.get_attribute
不會打印任何內容,因為該值為None
。
另外, <select>
標記首先沒有“值”屬性。 您要做的是獲取了<select>
標記,它都是子標記。 <select>
標記( <option>
標記)中的每個子代都有一個“值”屬性。 如果嘗試獲取該<select>
中所有<option>
標記的所有值,則應執行以下操作:
price=soup.find("select",{"id":"space-prices"})
# get all <options> in a list
options = price.find_all("option")
# for each element in that list, pull out the "value" attribute
values = [o.get("value") for o in options]
print(values)
#[u'\xa3360', u'\xa31,260', u'\xa35,460', u'\xa316,380', u'\xa365,520']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.