【问题标题】:Using beautiful soup - to extract string in a <div> tag?使用美丽的汤 - 在 <div> 标签中提取字符串?
【发布时间】:2018-02-20 18:52:40
【问题描述】:

对于这件事,我对 bs4 相当陌生,但我试图从网站上抓取一小部分信息:但它一直打印“无”,就好像标题或任何标签(如果我替换它)不存在一样.

项目由两部分组成:

  • 循环部分:(这似乎很简单)。
  • 解析器部分:我有一些问题 - 见下文。

我正在尝试遍历 URL 数组并从 wordpress 插件列表中抓取以下数据。请参阅下面的循环-

from bs4 import BeautifulSoup
import requests
#array of URLs to loop through, will be larger once I get the loop working correctly
plugins = ['https://wordpress.org/plugins/wp-job-manager', 'https://wordpress.org/plugins/ninja-forms']

项目:wordpress-plugins 的状态数据列表: - 大约有 50 个插件感兴趣!

https://wordpress.org/plugins/wp-job-manager
https://wordpress.org/plugins/ninja-forms
https://wordpress.org/plugins/participants-database ....and so on and so forth.

解析器部分: 所以这是我用漂亮汤的方法 - 在标签中提取字符串?

import bs4
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

my_url = "https://wordpress.org/plugins/participants-database/"
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()
page_soup = soup(page_html, "html.parser")

ttt = page_soup.find("div", {"class":#post-15991 > div.entry-meta > div.widget.plugin-meta"})
item = ttt.a.text
print(item)

背景:想要从此页面获取以下数据:

https://wordpress.org/plugins/participants-database/

我需要以下三行的数据-在上面提到的例子中

Version: <strong>1.29.3</strong>
Active installations: <strong>100,000+</strong>
Tested up to: <strong>4.9.4</strong>

查看我在这里找到的 xpath:

//*[@id="post-15991"]/div[4]/div[1]

//*[@id="post-15991"]/div[4]/div[1]/ul/li[1]
//*[@id="post-15991"]/div[4]/div[1]/ul/li[2]
//*[@id="post-15991"]/div[4]/div[1]/ul/li[3]
//*[@id="post-15991"]/div[4]/div[1]/ul/li[4]
//*[@id="post-15991"]/div[4]/div[1]/ul/li[5]
//*[@id="post-15991"]/div[4]/div[1]/ul/li[6]

【问题讨论】:

    标签: python linux wordpress xpath beautifulsoup


    【解决方案1】:

    您可以简单地获得所需的值:

    ttt = page_soup.find("div", {"class":"plugin-meta"})
    text_nodes = [node.text.strip() for node in ttt.ul.findChildren('li')[:-1:2]]
    

    text_nodes的输出:

    ['Version: 1.7.7.7', 'Active installations: 10,000+', 'Tested up to: 4.9.4']
    

    【讨论】:

    • 您好,亲爱的安德森 - 非常感谢您的快速回复 - 这超出了预期。简直不可思议。你帮了我很多 - 是的。你鼓励我潜入 python ......再次 - 非常感谢!
    猜你喜欢
    • 2020-03-17
    • 2019-11-07
    • 2016-09-11
    • 1970-01-01
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    • 2017-05-29
    • 2020-12-12
    相关资源
    最近更新 更多