web抓取中类多输入的处理

2024-04-16 07:51:30 发布

您现在位置:Python中文网/ 问答频道 /正文

enter image description here

您好,我正在尝试获取value=“36”,但我不知道如何处理这个类有多个输入的事实

我的代码如下:

## cdkitchen.com
url= 'http://www.cdkitchen.com/recipes/recs/32/Snowball_Cookies_II54545.shtml'
r = requests.get(url)
page_body = r.text
soup=BeautifulSoup(page_body, 'html.parser')
stat= soup.find('div', class_='col-md-4 col-sm-4 mb-20')
for a in stat.find('form', class_='change-servs-form'):
    print(a.get_value())

get_value()不起作用,我尝试了一些其他方法,但是我被阻止了,有没有一种简单的方法来指定要刮取的输入


Tags: 方法formcomurlgetvaluepagebody
2条回答

这就是在beautifulsoupfind方法
{'class': 'classname'}中正确指定类的方式

另外,使用soup.get('attribute')从给定的标记中获取任何属性(value

工作代码:

stat = soup.find('div', {'class': 'col-md-4 col-sm-4 mb-20'})
for a in stat.find('form', {'class': 'change-servs-form'}):
    print(a.get('value'))

36

注意:我更喜欢CSS选择器,但我不想对你的代码有太多的磨练。你应该调查一下:)

编辑

使用CSS选择器,从form内的每个input标记获取valueattr

stat = soup.find('form', {'class': 'change-servs-form'})
input_tags = stat.select('input')
for a in input_tags:
    print(a.get('value'))

36
21411
change servings
reset

另一种方式可以是下面的方式。使用css选择器:

import requests
from bs4 import BeautifulSoup

res = requests.get('http://www.cdkitchen.com/recipes/recs/32/Snowball_Cookies_II54545.shtml')
soup = BeautifulSoup(res.text, 'lxml')
item_name = '\n'.join([item['value'] for item in soup.select('.change-servs-form input')])
print(item_name)

输出:

36
21411
change servings
reset

相关问题 更多 >