【问题标题】:Iterating website URLs from a text file into BeautifulSoup w/ Python使用 Python 将文本文件中的网站 URL 迭代到 BeautifulSoup
【发布时间】:2019-10-23 15:59:04
【问题描述】:

我有一个 .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)

任何帮助将不胜感激,

谢谢

【问题讨论】:

    标签: python python-3.x beautifulsoup


    【解决方案1】:

    我不知道这是否对您有帮助,但是当您将其分配给 link 变量时,我已将 strip() 添加到 websitelink 并帮助我使您的代码正常工作。你可以试试看。

    websitelink = line.strip()

    【讨论】:

    • 就是这样!谢谢!但是为什么 .strip() 会突然让它工作呢?
    • 那是因为当你从文件中读取时,它有它的\r \n,你需要去掉它。当我看到你放在那里的照片时,我发现了这一点。
    猜你喜欢
    • 1970-01-01
    • 2014-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-06
    • 2020-08-02
    • 2020-02-21
    • 1970-01-01
    相关资源
    最近更新 更多