首页 > 解决方案 > 按照论坛中的链接使用 BS4 抓取线程(评论)

问题描述

我有一个有 3 个线程的论坛。我正在尝试抓取所有三个帖子中的数据。所以我需要按照每个帖子的href链接并抓取数据。这给了我一个错误,我不确定我错了什么......

import csv
import time
from bs4 import BeautifulSoup
import requests

source = requests.get('https://mainforum.com').text

soup = BeautifulSoup(source, 'lxml')

#get the thread href (thread_link)
for threads in soup.find_all('p', class_= 'small'):
    thread_name = threads.text
    thread_link = threads.a.get('href')# there are three threads and this gets all 3 links
    print (thread_link)

其余代码是我遇到问题的地方?

# request the individual thread links
for follow_link in thread_link:
    response = requests.get(follow_link)

    #parse thread link
    soup= BeautifulSoup(response, 'lxml')

    #print Data
    for p in soup.find_all('p'):
        print(p)

标签: pythonbeautifulsoup

解决方案


至于您的架构错误...

您收到架构错误,因为您一遍又一遍地覆盖一个链接。然后您尝试调用该链接,就好像它是链接列表一样。此时它是一个字符串,您只需遍历字符(以 开头h)因此出现错误。

请参阅此处:requests.exceptions.MissingSchema:无效的 URL 'h':未提供架构


至于一般查询以及如何解决这样的问题......

如果我要这样做,流程将如下所示:

  1. 获取三个href(类似于您已经完成的)
  2. 使用一个函数单独抓取线程href并返回您希望它们返回的任何内容
  3. 将返回的信息保存/附加到您想要的任何位置。
  4. 重复

可能是这样的

import csv
import time
from bs4 import BeautifulSoup
import requests

source = requests.get('https://mainforum.com')

soup = BeautifulSoup(source.content, 'lxml')

all_thread_info = []

def scrape_thread_link(href):
    response = requests.get(href)

    #parse thread link
    soup= BeautifulSoup(response.content, 'lxml')

    #return data
    return [p.text for p in soup.find_all('p')]

#get the thread href (thread_link)
for threads in soup.find_all('p', class_= 'small'):
    this_thread_info = {}
    this_thread_info["thread_name"] = threads.text
    this_thread_info["thread_link"] = threads.a.get('href')
    this_thread_info["thread_data"] = scrape_thread_link(this_thread_info["thread_link"])
    all_thread_info.append(this_thread_info)

print(all_thread_info)

原始问题中有很多未指定的内容,所以我做了一些假设。理想情况下,尽管您可以看到要点。

另请注意,我更喜欢使用.contentofresponse而不是.text


推荐阅读