简体   繁体   中英

get specific value with Beautiful Soup using python

I have this code that extracts all the numbers on the website if I want to get a specific value how can I do it? I did this but it doesn't work

import urllib
import re
import requests
from bs4 import *

    url = requests.get("http://python-data.dr-chuck.net/comments_216543.html")
    soup = BeautifulSoup(url.content, "html.parser")
    sum=0
    tags = soup('span')
    for tag in tags:
        y=str(tag)
        x= re.findall("[0-9]+",y)
        for i in x:
            print (i[1])

To get tag "Coby", you can use pass a custom function to .find() :

import requests
from bs4 import *

url = requests.get("http://python-data.dr-chuck.net/comments_216543.html")
soup = BeautifulSoup(url.content, "html.parser")

coby = soup.find(lambda tag: tag.name == "tr" and "Coby" in tag.text)

print(coby.get_text(separator=" "))

Output:

Coby 95

Or, to only get the comment, use .find_next() :

print(coby.find_next("span", class_="comments").get_text())

Output:

95

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM