【问题标题】:How to loop through multiple pages in multiple urls Python如何在多个url Python中循环多个页面
【发布时间】:2020-01-13 20:22:22
【问题描述】:

我有一个 url 列表,我希望我的代码遍历这些多个 url 的多个页面

urls = ['https://www.f150forum.com/f118/2019-adding-adaptive-cruise-454662/','https://www.f150forum.com/f118/adaptive-cruise-control-sensor-blockage-446041/']

comments = []

for url in urls:
    with requests.Session() as req:
        for item in range(1):
            response = req.get(url+"index{item}/")
            soup = BeautifulSoup(response.content, "html.parser")
            for item in soup.findAll('div',attrs={"class":"ism-true"}):
                result = [item.get_text(strip=True, separator=" ")]
                comments.append(result)


上面的代码通过了一个错误。你能告诉我如何循环浏览多个页面吗?我得到的错误是“NoneType”对象没有属性“findAll”

【问题讨论】:

  • 试试scrapy.org
  • 上面的代码通过一个错误如果你把错误告诉我们会很有帮助的。
  • 我认为r.content 应该是response.content
  • 我已经更新了我的问题
  • @anonymous13 : 你希望每页有多少条记录。第一个网址每页有 10 条记录,第二个网址每页有 7 条记录。

标签: python web-scraping beautifulsoup


【解决方案1】:

soup 可以返回None。 只有当汤有价值时才继续。

    soup = BeautifulSoup(response.content, "html.parser")
    if soup:  
        for item in soup.findAll('div',attrs={"class":"ism-true"}):
            result = [item.get_text(strip=True, separator=" ")]
            comments.append(result)

注意response.content 是二进制响应, response.text 是字符串形式吗?如果匹配始终失败,请尝试字符串形式。

如果“item”是一个数字,看起来你想要一个 f 字符串作为 url:

 for item in range(1):
        response = req.get(f"{url}index{item}/")

【讨论】:

  • 非常感谢 f"{url}index{item}/" 这对我有用。
猜你喜欢
  • 1970-01-01
  • 2020-07-01
  • 2019-05-26
  • 1970-01-01
  • 1970-01-01
  • 2012-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多