【问题标题】:Beautifulsoup Looping through Variable UrlBeautifulsoup 通过可变 URL 循环
【发布时间】: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


【解决方案1】:

您可以循环访问您的标签,为每个标签发送请求。

header = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0'}

TAGS = ['economy', 'food', 'sports', 'usa', 'health']
for tag in TAGS:
    resp = requests.get(f"https://www.yahoo.com/lifestyle/tagged/{tag}", headers=header)
    print(len(resp.text))

#341723
#442712
#447413
#368508
#445326

【讨论】:

    【解决方案2】:

    您似乎想分别插入 TAGS 中的每个值并为每个值执行请求。因此,您需要遍历 TAGS 并为每个标签提交请求。我希望你想要这样的东西:

    TAGS = ['economy', 'food', 'sports', 'usa', 'health']
    for tag in TAGS:
        resp = req.get(f'https://www.yahoo.com/lifestyle/tagged/{tag}',headers=header)
        soup = BeautifulSoup(resp.text, 'lxml')
        <process the page>
    

    【讨论】:

    • 注意未来:如果有人需要类似的东西。 Steve 的代码也运行良好。
    猜你喜欢
    • 2015-03-01
    • 2023-04-03
    • 2020-01-27
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 2014-02-24
    相关资源
    最近更新 更多