首页 > 解决方案 > 使用 Python 将文本文件中的网站 URL 迭代到 BeautifulSoup

问题描述

我有一个 .txt 文件,在我想要迭代的每一行上都有一个不同的链接,并解析为 BeautifulSoup( response.text , "html.parser")。我有几个问题。

我可以看到从文本文件中迭代的行,但是当我将它们分配给我的 requests.get(websitelink) 时,我以前工作的代码(没有迭代)不再打印我抓取的任何数据。

我收到的只是结果中的一些空白行。

我是 Python 和 BeautifulSoup 的新手,所以我不太确定自己做错了什么。我尝试将这些行解析为字符串,但这似乎不起作用。

import requests
from bs4 import BeautifulSoup
filename = 'item_ids.txt'

with open(filename, "r") as fp:
    lines = fp.readlines()
    for line in lines:

        #Test to see if iteration for line to line works
        print(line)

        #Assign single line to websitelink
        websitelink = line

        #Parse websitelink into requests
        response = requests.get(websitelink)
        soup = BeautifulSoup(response.text, "html.parser")

        #initialize and reset vars for cd loop
        count = 0
        weapon = ''
        stats = ''

        #iterate through cdata on page, and parse wanted data
        for cd in soup.findAll(text=True):
            if isinstance(cd, CData):
                #print(cd)
                count += 1
                if count == 1:
                    weapon = cd
                if count == 6:
                    stats = cd

        #concatenate cdata info
        both = weapon + " " + stats
        print(both)

代码应遵循以下步骤:

  1. 从文本文件中读取行(URL),并分配给变量以使用 request.get(websitelink)
  2. BeautifulSoup 抓取 CData 的链接并打印它
  3. 重复第 1 步和第 2 步,直到文本文件的最后一行(最后一个 URL)

任何帮助将不胜感激,

谢谢

标签: pythonpython-3.xbeautifulsoup

解决方案


我不知道这对你有没有帮助,但是当你将它分配strip()给你的link变量时,我已经在你的变量中添加了一个,websitelink并帮助我使你的代码工作。你可以试试。

websitelink = line.strip()


推荐阅读