【发布时间】:2021-02-03 16:53:02
【问题描述】:
我正在尝试存储从网站上抓取的一些数据。该网址超过 100 多个并且彼此相似。因此,我尝试在我的代码中使用带有 %s 标记的东西。
我的例如网址:
https://www.yahoo.com/lifestyle/tagged/food、
https://www.yahoo.com/lifestyle/tagged/sports、
https://www.yahoo.com/lifestyle/tagged/usa、
https://www.yahoo.com/lifestyle/tagged/health 并继续……
我的 Django+Bs4 循环:
from django.core.management.base import BaseCommand
from urllib.request import Request, urlopen
from bs4 import BeautifulSoup
from scraping.models import Job
import requests as req
header = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0'}
class Command(BaseCommand):
def handle(self, *args, **options):
TAGS = ['economy', 'food', 'sports', 'usa', 'health']
resp = req.get('https://www.yahoo.com/lifestyle/tagged/%s' % (TAGS),headers=header)
soup = BeautifulSoup(resp.text, 'lxml')
for i in range(len(soup)):
titles = soup.findAll("div", {"class": "StretchedBox Z(1)"})
print (titles)
错误信息是:
TypeError: not all arguments converted during string formatting
我一直在玩循环,但对此很陌生,无法弄清楚如何循环。我在这里想念什么? 更有知识的人可以指出我正确的方向吗?非常感谢
【问题讨论】:
-
鉴于
TAGS是一个字符串列表,您希望'https://www.yahoo.com/lifestyle/tagged/%s' % (TAGS)做什么?您显然希望单独插入 TAGS 中的每个值并为每个值执行请求。但是这条线不是循环的,那你怎么期望它发出多个请求呢?
标签: python beautifulsoup