python - 使用 beautifulsoup 从 'value' 属性中提取文本

标签 python html web-scraping beautifulsoup attributes

HTML代码:

<td id="ContentPlaceHolder1_ContentPlaceHolder1_Product_eBay1_tdBINPrice">
    <input id="ContentPlaceHolder1_ContentPlaceHolder1_Product_eBay1_txtBuyItNowPrice" name="ctl00$ctl00$ContentPlaceHolder1$ContentPlaceHolder1$Product_eBay1$txtBuyItNowPrice" 
    style="width:50px;" type="text" value="1435.97"/>                           
    <img id="ContentPlaceHolder1_ContentPlaceHolder1_Product_eBay1_imgCustomPriceCalculator" src="/images/ChannelPriceCustom.png" style="width:16px;"/>
</td>

我想在 'Value' 属性 ('1435.95') 中添加额外的文本

我尝试通过执行以下代码来做到这一点,但没有成功。

driver.get(someURL)
       page = driver.page_source
       soup = BeautifulSoup(page, 'lxml')
       price = soup.find('td', {'id' : re.compile('ContentPlaceHolder1_ContentPlaceHolder1_Product_eBay1_tdBINPrice')})

       print(price)

谢谢!

最佳答案

试试下面的代码。

from bs4 import BeautifulSoup

html='''<td id="ContentPlaceHolder1_ContentPlaceHolder1_Product_eBay1_tdBINPrice">
    <input id="ContentPlaceHolder1_ContentPlaceHolder1_Product_eBay1_txtBuyItNowPrice" name="ctl00$ctl00$ContentPlaceHolder1$ContentPlaceHolder1$Product_eBay1$txtBuyItNowPrice" 
    style="width:50px;" type="text" value="1435.97"/>                           
    <img id="ContentPlaceHolder1_ContentPlaceHolder1_Product_eBay1_imgCustomPriceCalculator" src="/images/ChannelPriceCustom.png" style="width:16px;"/>
</td>'''

soup = BeautifulSoup(html, 'html.parser')

textval=soup.select_one("input[name='ctl00$ctl00$ContentPlaceHolder1$ContentPlaceHolder1$Product_eBay1$txtBuyItNowPrice']")
print(textval['value'])

from bs4 import BeautifulSoup

html='''<td id="ContentPlaceHolder1_ContentPlaceHolder1_Product_eBay1_tdBINPrice">
    <input id="ContentPlaceHolder1_ContentPlaceHolder1_Product_eBay1_txtBuyItNowPrice" name="ctl00$ctl00$ContentPlaceHolder1$ContentPlaceHolder1$Product_eBay1$txtBuyItNowPrice" 
    style="width:50px;" type="text" value="1435.97"/>                           
    <img id="ContentPlaceHolder1_ContentPlaceHolder1_Product_eBay1_imgCustomPriceCalculator" src="/images/ChannelPriceCustom.png" style="width:16px;"/>
</td>'''

soup = BeautifulSoup(html, 'html.parser')

textval=soup.find("input" ,attrs={"name" : "ctl00$ctl00$ContentPlaceHolder1$ContentPlaceHolder1$Product_eBay1$txtBuyItNowPrice"})
print(textval['value'])

关于python - 使用 beautifulsoup 从 'value' 属性中提取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55750240/

相关文章:

jQuery:选择列表项,显示文本

jquery - 如何对齐两个 div 的底部边缘?

Python Dash - 结合两个回调函数

python - Django+PostgreSql : Can I run out of id/pk?

php - 正确的文件路径 img src,图像未加载 PHP HTML

c# - HtmlAgilityPack SelectNodes,处理

python - 抓取并下载 png 和 jpeg

python - 使用 Python 3 连接/连接 txt 文件中的行

python - 模块未找到错误: No module named 'jmespath'

xpath - Scrapy跟随javascript输入按钮