Только текст абзаца Python BeautifulSoup - PullRequest
1 голос
/ 18 марта 2019

Я очень новичок во всем, что связано с веб-копированием, и, насколько я понимаю, Requests и BeautifulSoup - путь к этому. Я хочу написать программу, которая отправляет мне по электронной почте только один абзац данной ссылки каждые пару часов (пробуя новый способ чтения блогов в течение дня) Скажем, у этой конкретной ссылки 'https://fs.blog/mental-models/' есть абзац на разных моделях.

from bs4 import BeautifulSoup
import re
import requests


url = 'https://fs.blog/mental-models/'

r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')

теперь у супа есть стена битов, прежде чем начинается текст абзаца: <p> this is what I want to read </p>

soup.title.string работает отлично, но я не знаю, как двигаться дальше, пожалуйста ... какие-либо направления?

спасибо

Ответы [ 3 ]

2 голосов
/ 18 марта 2019

Обведите soup.findAll('p'), чтобы найти все теги p, а затем используйте .text, чтобы получить их текст:

Кроме того, делайте все это в div с классом rte, так как вам не нужны абзацы нижнего колонтитула.

from bs4 import BeautifulSoup
import requests

url = 'https://fs.blog/mental-models/'    
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')

divTag = soup.find_all("div", {"class": "rte"})    
for tag in divTag:
    pTags = tag.find_all('p')
    for tag in pTags[:-2]:  # to trim the last two irrelevant looking lines
        print(tag.text)

OUTPUT

Mental models are how we understand the world. Not only do they shape what we think and how we understand but they shape the connections and opportunities that we see.
.
.
.
5. Mutually Assured Destruction
Somewhat paradoxically, the stronger two opponents become, the less likely they may be to destroy one another. This process of mutually assured destruction occurs not just in warfare, as with the development of global nuclear warheads, but also in business, as with the avoidance of destructive price wars between competitors. However, in a fat-tailed world, it is also possible that mutually assured destruction scenarios simply make destruction more severe in the event of a mistake (pushing destruction into the “tails” of the distribution).

1016 *

1 голос
/ 18 марта 2019

Вот решение:

from bs4 import BeautifulSoup
import requests
import Clock

url = 'https://fs.blog/mental-models/'  
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
data = soup.find_all('p')

result = []

for p in data:
    result.append(p.get_text())

Clock.schedule_interval(print(result), 60)
1 голос
/ 18 марта 2019

Если вам нужен текст всех тегов p, вы можете просто зациклить их, используя метод find_all:

from bs4 import BeautifulSoup
import re
import requests


url = 'https://fs.blog/mental-models/'

r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
print(soup)

data = soup.find_all('p')
for p in data:
    text = p.get_text()
    print(text)

EDIT:

Вот код для того, чтобы поместить их отдельно в список. Вы можете применить цикл в списке результатов, чтобы удалить пустую строку, неиспользуемые символы, такие как \n и т. Д.

from bs4 import BeautifulSoup
import re
import requests


url = 'https://fs.blog/mental-models/'

r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')

data = soup.find_all('p')
result = []
for p in data:
    result.append(p.get_text())

print(result)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...