python - 使用 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)
代码应遵循以下步骤:
- 从文本文件中读取行(URL),并分配给变量以使用 request.get(websitelink)
- BeautifulSoup 抓取 CData 的链接并打印它
- 重复第 1 步和第 2 步,直到文本文件的最后一行(最后一个 URL)
任何帮助将不胜感激,
谢谢
解决方案
我不知道这对你有没有帮助,但是当你将它分配strip()
给你的link
变量时,我已经在你的变量中添加了一个,websitelink
并帮助我使你的代码工作。你可以试试。
websitelink = line.strip()
推荐阅读
- c++ - 这是什么类型的 C++ 语法,我应该采取什么步骤来理解它
- scheme - 编写一个找到最小 k 的函数,使得 x 和函数之间的差异
- c# - 如何在 C# 中以特定顺序反转文件中的字节?
- ios - 有没有办法隐藏 UITableView 的页脚?
- javascript - 如果移动应用程序将在 React Native 中使用,那么在 React JS 中设置 Web 应用程序是否有优势
- javascript - 计算数组中元素的出现次数
- eclipse - 在克隆时获取无法打开-git-upload-pack-error-in-eclipse-
- jenkins - Build Pipeline Plugin - Jenkins - 仅显示子作业的 LAST Build Number 且仅显示一次(从 Post build 操作调用)
- php - Laravel:从子文件夹扩展文件
- python - 正则表达式查找子字符串,然后根据分隔符拆分