【问题标题】:storing data after scraping and parsing抓取和解析后存储数据
【发布时间】:2016-01-10 12:01:54
【问题描述】:

我有一个使用 Beautiful Soup 4 解析的 html 文件,这是我感兴趣的部分

[
 <td>Name :</td>,   <td>xyz</td>, 
 <td>Mobile :</td>, <td>180-14587962</td>, 
 <td>Company:</td>, <td>abc Comp</td>, 
 <td>Name :</td>,   <td>  </td>, 
 <td>Mobile :</td>, <td>  </td>, 
 <td>Company:</td>, <td>  </td>, 
 <td>Name :</td>,   <td>  </td>, 
 <td>Mobile :</td>, <td>  </td> 
]

我只需要分别提取 Name 和 Mobile(它们在解析树中处于同一级别)。我该怎么做?我已经尝试使用 soup.find_next_siblings method 但无法以所需格式存储数据( Number 和 Mobile 的两个单独列表)

【问题讨论】:

    标签: python python-3.x web-scraping beautifulsoup bs4


    【解决方案1】:

    我就是这样解决的

    for tag in soup.findAll('td'):
      if tag.text.strip("\n").strip(' ').strip("\n")== 'Name :':
          inter=tag.find_next_sibling()
          list_name.append(inter.text.strip("\n").strip(' ').strip("\n"))
      if tag.text.strip("\n").strip(' ').strip("\n")== 'Mobile :':
          inter=tag.find_next_sibling()
          list_mobile.append(inter.text.strip("\n").strip(' ').strip("\n"))
    

    遍历所有 td 标签以查找“名称:”或“手机:”并将下一个标签(包含值)添加到单独的列表中

    【讨论】:

      【解决方案2】:

      你可以使用类似的东西:

      from bs4 import BeautifulSoup
      html = """
       <td>Name :</td>,   <td>xyz</td>, 
       <td>Mobile :</td>, <td>180-14587962</td>, 
       <td>Company:</td>, <td>abc Comp</td>, 
       <td>Name :</td>,   <td>  </td>, 
       <td>Mobile :</td>, <td>  </td>, 
       <td>Company:</td>, <td>  </td>, 
       <td>Name :</td>,   <td>  </td>, 
       <td>Mobile :</td>, <td>  </td> 
      """
      soup = BeautifulSoup(html, "lxml")
      x = soup.find_all("td")
      print x[1]
      print x[3]
      

      标准输出

      <td>xyz</td>
      <td>180-14587962</td>
      

      演示

      http://ideone.com/xDzeni

      【讨论】:

      • 问题是这个结构是重复的,不会到此结束。所以我只会根据你的回答得到第一对,而不是剩下的。
      • 您需要使用正则表达式来获取所有匹配项。您能发布更完整的示例吗?
      • 结构不断重复,带有 3 个 td 标签(移动公司名称)...就是这样
      猜你喜欢
      • 1970-01-01
      • 2013-08-28
      • 1970-01-01
      • 2012-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多