【问题标题】:Getting word count from webpage从网页获取字数
【发布时间】:2021-04-03 00:38:05
【问题描述】:
import requests
from bs4 import BeautifulSoup

# Cleans text (removes any punctuation)
def CleanText(text):
    text = str(text)
    forbidden = [r'\n', r'.', r'?', r'!', r'(', r')']
    for i in forbidden:
        text.replace(i, '')
    return text

# returns count of a word from a page
def ReturnCount(url, word):
    r = requests.get(url, allow_redirects=False)
    soup = BeautifulSoup(r.content, 'lxml')
    words = str(soup.find(text=lambda text: text and word in text))
    words = CleanText(words.lower())
    words = words.split()
    return words.count(word.lower())

我正在尝试获取网页上特定单词的频率(出现)。但是,我总是得到 0 作为输出。

计数为 0,尽管该词多次出现 输出:0

【问题讨论】:

  • 能否也提供urlword 进行复制。

标签: python web-scraping beautifulsoup lxml


【解决方案1】:

发生了不同的事情:

  • 您尝试使用find() 获取所有text,但仅获得第一次出现
  • 尝试使用find_all() 来获取所有匹配项
  • 不确定您的 lambda 在那里做什么
  • soup.body.find_all(text=True)body 标记中获取所有text,处理列表并通过''.join([t for t in soup.body.find_all(text=True)]) 加入string

示例:

import requests
from bs4 import BeautifulSoup

# Cleans text (removes any punctuation)
def CleanText(text):
    text = str(text)
    forbidden = [r'\n', r'.', r'?', r'!', r'(', r')']
    for i in forbidden:
        text.replace(i, '')
    return text

# returns count of a word from a page
def ReturnCount(url, word):
    r = requests.get(url, allow_redirects=False)
    soup = BeautifulSoup(r.content, 'lxml')
    words = ''.join([t for t in soup.body.find_all(text=True)])
    words = CleanText(words.lower())
    words = words.split()
    return words.count(word.lower())

ReturnCount('https://www.microsoft.com/de-de/microsoft-365/word','word')

输出: 13

【讨论】:

  • 它没有给出任何结果。它只是通过,没有返回任何值
  • 这行你改了吗words = str(soup.find(text=lambda text: text and word in text)) --> words = ''.join([t for t in soup.body.find_all(text=True)])
【解决方案2】:

我不确定你为什么需要

words = str(soup.find(text=lambda text: text and word in text))

简单一点

def ReturnCount(url, word):
    r = requests.get(url, allow_redirects=False)
    soup = BeautifulSoup(r.content, 'html.parser')
    words = CleanText(soup.text.lower())
    words = words.split()
    return words.count(word.lower())

wordCount = ReturnCount('http://example.com/', 'in')
print(wordCount) # 3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    • 2011-12-21
    • 2021-07-17
    相关资源
    最近更新 更多