#python #web-scraping #beautifulsoup #lxml
#python #очистка веб-страниц #beautifulsoup #lxml
Вопрос:
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
Комментарии:
1. Не могли бы вы также предоставить
url
иword
воспроизвести, пожалуйста.
Ответ №1:
Происходят разные вещи:
- Вы пытаетесь получить все
text
find()
, что получает только первое вхождение - Вместо этого попробуйте использовать
find_all()
, который получает все вхождения - Не уверен, что вы
lambda
там делаете soup.body.find_all(text=True)
получить всеtext
изbody
тега, обработать список и присоединиться''.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
Комментарии:
1. Это не дает никакого результата. Он просто проходит, не возвращая никакого значения
2. Вы изменили эту строку
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