【问题标题】:requests_html: How to structure code to include sub-pages?requests_html:如何构造代码以包含子页面?
【发布时间】:2021-03-07 20:49:56
【问题描述】:

如何构建我的代码以包含有时在运行循环中的分页。我还没有使用def。也许这就是答案。但是在找了几天之后,我被卡住了。我正在寻找一个高水平的答案。

这是我的基本结构:

import requests_html
from requests_html import HTMLSession
from requests_html import HTML
import re
import pandas as pd
from time import sleep
from random import randint
session = HTMLSession()

from url retrieve links for states with providers

(loop) from states retrieve urls for cities with providers

        from city_page in cities:
            Retrieve data about individual providers from each "card"
            (max 10 "cards" per page) Everything is fine up to this point.

            Here is where I am lost. Sometimes a city only has one or two providers and that works 
            just fine. Sometimes there are 50+ providers at 10 per page. There are links to the 
            extra pages at the bottom of the container/ [<element>].

我一般如何构建我的代码以在出现额外页面时循环它们?然后返回到包含循环,以便它可以继续到下一个城市?我不知道如何将额外的 url 注入现有循环。

【问题讨论】:

  • 建议你开始做这件事并让一些东西发挥作用,然后——并且只有在需要时——看看是否有机会改进代码。
  • 谢谢巴尼。我已经尝试过了,目前我正在尝试一个新的 def 函数,将抓取循环变成一个 def(我对这些仍然非常陌生),然后尝试在两种情况下调用它(仅主页和/或存在的子页面)并在可用时迭代或遍历。我不喜欢在这里提问,这么多严厉的回答会责备提问者。所以当我在这里问的时候,我感觉就像撞到了墙一样。感谢您的鼓励,非常感谢。

标签: python python-3.x pandas python-requests-html


【解决方案1】:

所以我想出了一个满足我需求的解决方案。它可能不是 Pythonic。 它允许我控制城市级别的搜索深度。 我添加了一个输入,用于在城市级别循环遍历子页面的数量(深度)(默认为 1)。 我添加了一个额外的 for 循环 for page in pages 并将我的主循环嵌套在其中。 当没有找到元素(EC:分页)时,主循环将中断并移动到下一个城市主页。

root_url = input("enter root URL here")
sub_pages = input("number of sub-pages to scrape")

for loop (from root_url retrieve links for states with providers)
    states_urls = 

for loop (from states_urls retrieve urls for cities with providers)
    city_list_urls = 

for loop (from city_list_urls  get.city)
    clink = get(city)
          
    for page in sub_pages [1:]:
        print("Retriving Listings From City Page: ", page)
        urll = session.get(city + "?pagenumber=" + str(page))
        cards = urll.get(containing element)

        for card in cards:
            main scraping code is here
            scrape and parse each "card"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多