使用django中的漂亮汤进行网络抓取

时间:2019-04-07 06:14:02

标签: django web-scraping

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

  

scrapper.py

from bs4 import BeautifulSoup
import requests


def scrap(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(scrap())

2 个答案:

答案 0 :(得分:1)

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

处理

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

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

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

enter image description here

所以这部分

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

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

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

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

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

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

dict["title"]

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

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

答案 1 :(得分:0)

request.get为您下载dom数据,并为美丽的汤标签下载与dom的键/标签相对应的dom中的每个数据,并创建事物字典。因此,当您 bs.select(“。nws__title--card> h2”)时,表示您正在提取标签为 .nws__title--card> h2 的数据,该数据将返回数组。现在,您通过执行 [0] 并请求文本部分来选择数组中的第一个元素。这就是全部的工作方式。有关更多详细信息,请阅读https://www.crummy.com/software/BeautifulSoup/bs4/doc/

相关问题