【问题标题】:Struggling to scrape a telegram public channel with BeautifulSoup努力用 BeautifulSoup 刮一个电报公共频道
【发布时间】:2021-03-29 21:11:57
【问题描述】:

我正在使用 BeautifulSoup 练习网页 scraping,但我很难完成打印包含我已scraped

的项目的字典

目标网络可以是任何电报公共频道(网络版),我假装收集并添加文本消息、时间戳、视图和图像 URL(如果存在附加到帖子)作为字典的一部分。

我已经检查了 4 个元素的代码,但与图像 url 相关的那个没有类或跨度,所以我通过正则表达式结束了 scraping 它们。其他 3 个元素很容易检索。

让我们分部分来:

导入模块

from bs4 import BeautifulSoup
import requests
import re

从公共频道获取图片url的功能

def pictures(url):
    r = requests.get(url)
    soup = BeautifulSoup(r.text, 'lxml')
    link = str(soup.find_all('a', class_ = 'tgme_widget_message_photo_wrap')) #converted to str in order to be able to apply regex
    image_url = re.findall(r"https://cdn4.*.*.jpg", link)
    return image_url

获取短信、时间戳和浏览量的汤

picture_list = pictures(url)
url = "https://t.me/s/computer_science_and_programming"

channel = requests.get(url).text
soup = BeautifulSoup(channel, 'lxml')
tgpost = soup.find_all('div', class_ ='tgme_widget_message')
full_message = {}
for content in tgpost:
    full_message['views'] = content.find('span', class_ = 'tgme_widget_message_views').text
    full_message['timestamp'] = content.find('time', class_ = 'time').text
    full_message['text'] = content.find('div', class_ = 'tgme_widget_message_text').text
    print(full_message)

如果有人可以帮助我,我将不胜感激,我是 Python 新手,我不知道该怎么做

  1. 检查帖子是否包含图片,如果有,请将其添加到字典中
  2. 打印字典,包括 image_url 作为键和 url 作为每个帖子的值。

非常感谢

【问题讨论】:

  • “报废”?正确的术语是scraping(和scrapescrapedscraper
  • 嗨,巴尼,感谢您的更正。我不是以英语为母语的人,我写作时经常会出现一些错别字。关于问题本身......你有一个我可以尝试的答案吗?

标签: python for-loop web-scraping beautifulsoup telegram


【解决方案1】:

我想你想要这样的东西。

from bs4 import BeautifulSoup
import requests, re

url = "https://t.me/s/computer_science_and_programming"

channel = requests.get(url).text
soup = BeautifulSoup(channel, 'lxml')
tgpost = soup.find_all('div', class_ ='tgme_widget_message')
full_message = {}

for content in tgpost:
    full_message['views'] = content.find('span', class_ = 'tgme_widget_message_views').text
    full_message['timestamp'] = content.find('time', class_ = 'time').text
    full_message['text'] = content.find('div', class_ = 'tgme_widget_message_text').text

    if content.find('a', class_ = 'tgme_widget_message_photo_wrap') != None :
        link = str(content.find('a', class_ = 'tgme_widget_message_photo_wrap'))
        full_message['url_image'] = re.findall(r"https://cdn4.*.*.jpg", link)[0]
    elif 'url_image' in full_message:
        full_message.pop('url_image')

    print(full_message)

【讨论】:

  • 您好 Arlene,非常感谢您抽出宝贵时间审阅并为我的问题提供可能的答案。不幸的是,我无法按照您的建议进行操作。我发现的第一个问题是,如果图像未转换为字符串,我无法使用 findall 方法检索图像 url。即使我为 if 块内相关的 3 个调用执行 str(),我也没有得到我想要的。
  • 我已经更正了代码。我认为它现在应该可以工作了。
  • 可爱的阿琳!再次感谢您帮助我解决这个问题。您越来越接近解决方案,但您遇到的问题比我在之前的一些测试中遇到的问题。使用您当前的代码,您总是会为所有帖子创建一个 image_url 链接,即使是那些没有图片的帖子
  • 添加最后一个条件应该可以解决问题
  • 绝对精彩!非常感谢小男孩和祝贺!试了几天还是不行!
猜你喜欢
  • 2022-11-01
  • 2021-01-05
  • 2017-11-22
  • 1970-01-01
  • 1970-01-01
  • 2016-05-30
  • 1970-01-01
  • 2021-11-12
  • 2018-05-16
相关资源
最近更新 更多