簡體   English   中英

使用 BeautifulSoup 在 Python 中按元素抓取 HTML

[英]Scraping HTML by elements in Python with BeautifulSoup

我試圖總結我從html中刮取的值,但是總和看起來很奇怪。(它顯然低於實際值。)

我查看了其他人的代碼,我注意到他們使用re.findall()來查找 html 中的數字。

我的問題是,為什么我不能直接從 html 中抓取內容元素? 我的代碼在上面,底部是其他人的代碼與我的代碼不同的代碼的一部分。

提前感謝您的回答!

# load in the required packages for reading HTML

from urllib.request import urlopen
from bs4 import BeautifulSoup #parser for HTML
import ssl
import re
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

#open the url
url = 'http://py4e-data.dr-chuck.net/comments_874984.html'
html = urlopen(url, context = ctx).read()
soup = BeautifulSoup(html, "html.parser")

# Retrive the information form url
spans = soup('span')
sum = 0
for span in spans:
    x = span.contents[0]
    for n in x:
        sum = sum + int(n)
print(sum)
sum=0
# Retrieve all of the anchor tags
tags = soup('span')
for tag in tags:
    # Look at the parts of a tag
    y=str(tag)
    x= re.findall("[0-9]+",y)
    for i in x:
        i=int(i)
        sum=sum+i
print(sum)

如果我理解正確,這應該會讓你到達那里:

counter = 0
for comment in soup.select('span.comments'):
    counter+=int(comment.text)
print(counter)

甚至更短:

comments = [int(comment.text) for comment in soup.select('span.comments')]
print(sum(comments))

兩種情況下的輸出:

2266

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM