【问题标题】:web scraping using beautiful soup in django在 django 中使用美丽的汤进行网页抓取
【发布时间】:2019-04-07 06:14:01
【问题描述】:

此代码运行良好。但我想知道它是如何工作的。 谁能帮我解释一下这段代码??

scraper.py

from bs4 import BeautifulSoup
import requests


def scrape(url="https://www.onlinekhabar.com/2018/12/724699"):
    try:
        res = requests.get(url)
        # print(res.text)
        # print(res.encoding)
        res.encoding = "utf-8"
        bs = BeautifulSoup(res.text, "html.parser")

        dict = {}
        dict["title"] = bs.select(".nws__title--card > h2")[0].text
        dict["published"] = bs.select(".post__time > span")[0].text
        dict["description"] = bs.select(".main__read--content")[0].text

        return dict
    except:
        return None

if __name__ == '__main__':
    print(scrape())

【问题讨论】:

    标签: django web-scraping


    【解决方案1】:

    XHR GET 请求通过 requests 库发送到该 url。响应对象html由BeautifulSoup.处理

    CSS 选择器语法用于从生成的BeautifulSoup 对象中检索信息。

    .nws__title--cardclass selector。选择具有类属性nws__title--card 的元素。那么> 是一个child combinator,指定右边的h2 标签元素必须是左边指定类的元素的子元素。 h2 是type selector

    如果您在开发工具元素选项卡中输入该选择器,您将看到只有一个匹配项

    所以,这部分

    select(".nws__title--card > h2")
    

    根据传递给“”内select的选择器返回所有匹配元素的列表。那么

    select(".nws__title--card > h2")[0]
    

    选择第一个元素。在这种情况下,您可以简单地将其替换为只返回一个匹配项的方法(然后不需要索引):

    select_one(".nws__title--card > h2")
    

    h2 是一个标题标签。它正在从页面获取标题。然后将其作为 title 键的值对添加到字典中

    dict["title"]
    

    相同的逻辑适用于匹配并添加到字典中的其他项目。

    如果处理成功则返回字典,如果失败则返回none

    【讨论】:

    • 这回答了你的问题吗?
    【解决方案2】:

    request.get 会为您下载 dom 数据,并为 dom 中的每个数据标记与其键/标记相对应的美丽汤,并创建一个字典之类的东西。因此,当您 bs.select(".nws__title--card > h2") 时,这意味着您正在提取带有标签 .nws__title--card > h2 的数据,该标签返回一个大批。现在,您通过执行 [0] 并请求文本部分来选择数组中的第一个元素。这就是一切的运作方式。更多详情请阅读https://www.crummy.com/software/BeautifulSoup/bs4/doc/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-30
      • 1970-01-01
      • 2019-05-05
      • 1970-01-01
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多