首页 > 解决方案 > BS4 python脚本运行时立即崩溃,但看代码应该没问题

问题描述

我写了以下代码。这可能不是最漂亮的,但我试过了。当我运行它时,它会创建 links.txt 文件,但实际脚本会立即崩溃,而不会在 cmd 上显示任何错误。我尝试研究 BS4,我真的认为这应该可行。

这是我试图开始工作的初始脚本,因此我最终可以将其更改为仅抓取“卡片”类中的链接,但事实上它甚至无法抓取我想了解我做错了什么的所有链接。

import requests
import time
from bs4 import BeautifulSoup
import sys

sys.stdout = open("links.txt", "a")

for x in range(0, 10):
    try:
        URL = f'https://wesbite.com/downloads/{x}/'
        page = requests.get(URL)
        time.sleep(5)

        soup = BeautifulSoup(html, 'html.parser')

        links_with_text = []
        for a in soup.find_all('a', href=True): 
            if a.text: 
                links_with_text.append(a['href'])
                print(links_with_text)
    except:
        continue

我最终尝试抓取的 Card 类的示例:

  <div class="card-content">
    <div class="center">
      <a target="_blank" href="https://website.com/username/">username</a>

我接受了您的建议,删除了例外,并意识到我的缩进不一致。在修复该问题并更改 page.text 之后,它似乎可以工作。下面的代码:

import requests
import time
from bs4 import BeautifulSoup
import sys

sys.stdout = open("links.txt", "a")

for x in range(0, 10):
    try:
        URL = f'https://wesbite.com/downloads/{x}/'
        page = requests.get(URL)
        time.sleep(5)

        soup = BeautifulSoup(page.text, 'html.parser')

        links_with_text = []
        for a in soup.find_all('a', href=True):
            if a.text: 
                links_with_text.append(a['href'])
                print(links_with_text)
    except Exception as e:
        print('something went wrong')

标签: pythonweb-scrapingbeautifulsoup

解决方案


html变量 inBeautifulSoup(html, 'html.parser')未在您发布的代码中定义,我的猜测是引发异常,该异常被您的块catch抑制。删除try...catch代码并运行它,异常是有用的信息,以这种方式抑制它们会阻止您发现问题。


推荐阅读