【问题标题】:parsing css selector with beautifulsoup用beautifulsoup解析css选择器
【发布时间】:2018-08-19 07:48:42
【问题描述】:

我正在使用 CSS 选择器通过 beautifulsoup 4 模块从网络上抓取数据。

查看示例代码:

# pull website
res = requests.get('https://dailystoic.com/epictetus/')

#parse file
soup = bs4.BeautifulSoup(res.text, 'html.parser')

# CSS selector
elems = soup.select('body > div.wrap.container > div > main > article > div.entry-content > p:nth-child(1) > em > a:nth-child(3)')

# take content and store in variable
content = elems[0].text.strip()

# print content
print(content)

我想要来自超链接的 html 文本。我不想要 URL,而是超链接所说的内容。

【问题讨论】:

    标签: python html css beautifulsoup


    【解决方案1】:

    使用:nth-of-type() 代替nth-child()

    import bs4, requests
    res = requests.get('https://dailystoic.com/epictetus/')
    soup = bs4.BeautifulSoup(res.text, 'html.parser')
    elems = soup.select('body > div.wrap.container > div > main > article > div.entry-content > p:nth-of-type(1) > em > a:nth-of-type(3)')
    print(elems[0].text)
    

    .text 获取超链接的内容 - link text。如果你想要这个 URL,你可以这样做:elems[0].attrs['href']

    输出:

    Epictetus

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-27
      • 2012-04-28
      • 1970-01-01
      • 2011-02-06
      相关资源
      最近更新 更多