Skip to main content
 首页 » 编程设计

python之使用 Python 和 BeautifulSoup 查找特定表格单元格值,然后打印整行

2025年05月04日16EasonJim

我有一个正在使用 BeautifulSoup 抓取的表格,我试图让它在某个单元格具有特定字符串时打印整行。下面的代码完全没有打印任何内容,我不明白为什么。如果我没有 for 循环而我只是打印数据变量,我会得到大量信息,所以它与我的 for 循环有关。

问题是,我永远不知道“Check”这个词会出现在哪里,也不知道它会在我的表格中出现多少次,所以我不能只看索引。我看过 Using Python and BeautifulSoup to Parse a Table ,但它看起来只是在寻找标签,而不是特定的字符串。我尝试使用此信息:http://www.briancarpio.com/2012/12/02/website-scraping-with-python-and-beautiful-soup/ , 但它确切地知道要与哪些索引对话,所以它在这里对我没有用。

有什么想法吗?

nextpage=logged_in.read() #let's read the page once we get logged in 
soup=BeautifulSoup(nextpage, "lxml") #BeautifulSoup told me to do this 
table = soup.findAll("table", {'class':'table2'}) #Find the table we want to work with 
data = [[td.findChildren(text=True) for td in tr.findAll("td")] for tr in table] #Find the cells for each table row 
 
for line in table: #if you see a line in the table 
    if line.find('Check'): #and you find the specific string 
        print line #print it  
print "Hey, this did run!" #debug statement 

请您参考如下方法:

有两个可能的问题。

第一个(也是最有可能的)是您混淆了标签和字符串。在你的代码中你有

for line in table: #if you see a line in the table 
    if line.find('Check'): #and you find the specific string 
        print line #print it  

第一行给你一个 line这是一个标签。然后您正在使用 find BeautifulSoup 的方法不是 python,所以你实际上是在寻找一个名为 Check 的 tag ,而不是字符串“检查”。没有 Check标签,这样打印行永远不会被执行。

第二个选项是您实际使用 python find方法将返回单词“Check”在字符串中的位置。由于您的支票是标签中唯一的字符串 <span style="color:green">Check</span> , python find将返回 0,因此您的 if陈述将是错误的。 (我不认为这是正在发生的事情,但您始终需要小心,您希望 0 表示 false 而不是 0)

我会将您的代码更改为以下内容并运行它:

for line in table: #if you see a line in the table 
    if line.get_text().find('Check') > -1 : #and you find the specific string 
         print line #print it  

此代码执行 get_text()从标签中获取字符串,然后执行 Python 字符串 find查看“检查”是否在字符串中。如果不是,它将返回 -1。