因此,我正試圖從一個網站上刮取資料,并獲得特定的值,以便在以后的計算中使用,但我在利用我刮取的資料并從中提取我想要的值時遇到了困難。目前,我的情況是這樣的:
import requests
from bs4 import BeautifulSoup
header = {
'User-Agent': 'Mozilla/5.0 (X11; Linux i686 on x86_64)'。
}
url = 'https://cars.usnews.com/cars-trucks/ram/1500/2021/specs/1500-tradesman-4x2-quad-cab-6-4-box-414114'/span>
page = requests.get(url, headers=header) # 更改頭檔案或被阻止。
soup = BeautifulSoup(page.content, 'html.parser')
specs = soup.find_all('div', class_="trim-specs column small-12" )
spec_values = []
for spec in specs:
spec_values.extend(spec.find_all('li')
towing = [x for x in spec_values if 'Max Trailering Capacity(lbs.
print(towing)
從這里我得到這個輸出。
[<li>最大拖曳能力(磅):7730</li>]
如何才能直接拉出拖曳能力?
我怎樣才能從這里拉出7330的數值呢?
這是我發現的一種方法,但它對不是整數的值不起作用
這是我發現的一種方法。
towing_num = [int(i) for i in str(towing) if i. isdigit()]
towing_cap = int(''/span>.join(map(str, towing_num))
print(towing_cap)
這給了我7730作為輸出,但這個方法對任何帶小數的數字都不起作用。是否有更直接的方法來獲得這個值?
預先感謝
uj5u.com熱心網友回復:
看一下頁面,你可以用:分割規格,然后第二個元素是你的數字。然后你可以在上面應用int()或float():
import requests
from bs4 import BeautifulSoup
header = {"User-Agent": "Mozilla/5.0 (X11; Linux i686 on x86_64)"}。
url = "https://cars.usnews.com/cars-trucks/ram/1500/2021/specs/1500-tradesman-4x2-quad-cab-6-4-box-414114"/span>
page = requests.get(url, headers=header) # change headers or get blocked[/span
soup = BeautifulSoup(page.content, "html.parser")
#加載所有的規格到`specs`串列。
specs = []
for li in soup.select(".trim-specs li:not(.subheader)")。
specs.append([w.strip() for w in li.text.split(" :") ])
# find "Max Trailering Capacity (lbs.)" in specs:
for s in specs:
if "最大拖曳能力(磅)" in s:
print("{}是{}"。 format(s[0], int(s[1] ))
break。
印刷品:
最大的拖車容量(磅)是7730。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/331299.html
標籤:
