【发布时间】:2024-07-02 20:30:01
【问题描述】:
我尝试为 Reddit 的 /r/all 创建一个网络爬虫,用于收集热门帖子的链接。我一直在 YouTube 上关注thenewboston's web crawler tutorial series 的第一部分。
在我的代码中,我删除了 while 循环,该循环在 thenewboston 的情况下设置了要抓取的页面数量的限制(我只是去爬取 /r/all 的前 25 个帖子,只有一页)。当然,我已经进行了这些更改以适应我的网络爬虫的目的。
在我的代码中,我已将 URL 变量更改为“http://www.reddit.com/r/all/”(原因很明显),将 Soup.findAll 可迭代更改为 Soup.findAll('a', {'class': 'title may-blank loggedin'})(title may-blank loggedin 是帖子标题的类在 Reddit 上)。
这是我的代码:
import requests
from bs4 import BeautifulSoup
def redditSpider():
URL = 'http://www.reddit.com/r/all/'
sourceCode = requests.get(URL)
plainText = sourceCode.text
Soup = BeautifulSoup(plainText)
for link in Soup.findAll('a', {'class': 'title may-blank loggedin'}):
href = 'http://www.reddit.com/r/all/' + link.get('href')
print(href)
redditSpider()
我在每行之间使用print 语句进行了一些业余错误检查,似乎没有执行 for 循环。
要了解或比较 thenewboston 的代码和我的代码,请跳到他的迷你系列的第二部分,并在他的视频中找到显示他的代码的位置。
编辑: thenewboston 应要求提供的代码:
import requests
from bs4 import BeautifulSoup
def trade_spider(max_pages):
page = 1
while page <= max_pages:
url = 'https://buckysroom.org/trade/search.php?page=' + str(page)
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text)
for link in Soup.findAll('a', {'class': 'item-name'}):
href = 'http://buckysroom.org' + link.get('href')
print(href)
page += 1
trade_spider()
【问题讨论】:
标签: python for-loop beautifulsoup web-crawler reddit