python - 用漂亮的汤和 Pandas 刮 table 时如何保留链接

标签 python pandas beautifulsoup

使用 Beautiful soupPandas 抓取网页以获取表格。其中一列有一些网址。当我将 html 传递给 pandas 时,href 丢失了。

有没有办法只为该列保留 url 链接?

示例数据(为更好地适应实际情况而编辑):

  <html>
        <body>
          <table>
              <tr>
               <td>customer</td>
               <td>country</td>
               <td>area</td>
               <td>website link</td>
             </tr>
             <tr>
               <td>IBM</td>
               <td>USA</td>
               <td>EMEA</td>
               <td><a href="http://www.ibm.com">IBM site</a></td>
            </tr>
          <tr>
            <td>CISCO</td>
            <td>USA</td>
            <td>EMEA</td>
            <td><a href="http://www.cisco.com">cisco site</a></td>
         </tr>
           <tr>
            <td>unknown company</td>
            <td>USA</td>
            <td>EMEA</td>
            <td></td>
         </tr>
       </table>
     </body>
  </html>

我的 python 代码:

    file = open(url,"r")

    soup = BeautifulSoup(file, 'lxml')

    parsed_table = soup.find_all('table')[1] 

    df = pd.read_html(str(parsed_table),encoding='utf-8')[0]

 df

输出(导出为 CSV):

customer;country;area;website
IBM;USA;EMEA;IBM site
CISCO;USA;EMEA;cisco site
unknown company;USA;EMEA;

df 输出正常,但链接丢失。我需要保留链接。至少是网址。

有什么提示吗?

最佳答案

pd.read_html 假设您感兴趣的数据在文本中,而不是标签属性中。然而,自己刮表并不难:

import bs4 as bs
import pandas as pd

with open(url,"r") as f:
    soup = bs.BeautifulSoup(f, 'lxml')
    parsed_table = soup.find_all('table')[1] 
    data = [[td.a['href'] if td.find('a') else 
             ''.join(td.stripped_strings)
             for td in row.find_all('td')]
            for row in parsed_table.find_all('tr')]
    df = pd.DataFrame(data[1:], columns=data[0])
    print(df)  

产量

          customer country  area          website link
0              IBM     USA  EMEA    http://www.ibm.com
1            CISCO     USA  EMEA  http://www.cisco.com
2  unknown company     USA  EMEA                      

关于python - 用漂亮的汤和 Pandas 刮 table 时如何保留链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42285417/

相关文章:

python - “Unknown String Format” - 解析 pandas dataframe 中的 URL 时出错

python - 如何用 pandas reshape 数据框

python - Beautifulsoup 未返回页面的完整 html

python - 解析 JSON 对象时,保留字作为数据类中的属性名称

python - Django/Graphene 突变不适用

python - Horovod 和 Tensorflow 估计器

selenium - 如何解决 urllib3.exceptions.MaxRetryError : HTTPConnectionPool(host ='127.0.0.1' , port=58408): Max retries exceeded with url

python - 根据 pandas 的条件计算天数差异

python - 什么是 R 函数(如 str()、summary() 和 head())的 Python pandas 等价物?

python - 如何在具有多个表的网页上调用特定表