【发布时间】: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)
代码应遵循以下步骤:
- 从文本文件中读取行 (URL),并分配给变量以使用 request.get(websitelink)
- BeautifulSoup 抓取 CData 的链接并打印出来
- 重复第 1 步和第 2 步,直到文本文件的最后一行(最后一个 URL)
任何帮助将不胜感激,
谢谢
【问题讨论】:
标签: python python-3.x beautifulsoup