【问题标题】:bs4) How many request does occur for each time parsing html?bs4) 每次解析 html 时会发生多少请求?
【发布时间】:2019-10-15 05:42:53
【问题描述】:

我通过requests 获得了 html 源代码,我想将它们解析为打击(sudo 代码):

import requests
from bs4 import BeautifulSoup

response = requests.get('https://www.example.com', headers=headers, params=params)

html_doc = response.text
soup = BeautifulSoup(html_doc, 'html.parser')

item_ls = []
for elem in soup.select('.items'):
    item_ls.append(elem.text)

但我不确定BeutifulSoup obj.请求数据,每次我通过for loop(尤其是在执行elem.text 时)迭代元素,或者我可以使用 obj.作为本地html源,不像selenium

我需要尽量减少请求的数量以避免被阻止。

【问题讨论】:

  • 在您的代码中发生 HTTP 请求的唯一时间是在 requests.get 调用中。其他一切都是本地的。
  • @rdas 感谢您的回答!我在哪里可以找到相关的事实?我在官方文档中找不到。
  • Bs4 是一个 html 解析器。一旦您从requests.get 获得 html,一切都是本地的 - 因为您已经拥有整个 HTML。 Selenium 可能会进行额外的 HTTP 调用,因为 webdriver 还可以执行 javascript - 这会进行更多的 http 调用。

标签: python-3.x beautifulsoup python-requests


【解决方案1】:

没有。 BeautifulSoup 不会进行额外的 HTTP 调用——它只是一个 HTML 解析器。

import requests
from bs4 import BeautifulSoup

response = requests.get('https://www.example.com', headers=headers, params=params)  # <- the only HTTP call being made here

html_doc = response.text  # <- You have the whole HTML here
soup = BeautifulSoup(html_doc, 'html.parser')

item_ls = []
for elem in soup.select('.items'):  # <- Everything is local
    item_ls.append(elem.text)

Selenium 的工作方式略有不同。由于 selenium webdriver 更像是一个浏览器,它也运行嵌入在 HTML 中的 javascript - 这可能会进行额外的 HTTP 调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-22
    • 2014-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多