[英]Scrape data from table
首先,我尝试使用bs4,但是该表不是纯HTML文本,这就是为什么我移至selenium
我正在尝试抓取表数据,但是我不知道如何获取信息。
我现在所拥有的是:
table = browser.find_element_by_id("name_list")
cell = table.find_elements_by_xpath("//td[@style='text-align:center']")
表数据显示如下:
<td style="text-align:center" class="left"><script
type="text/javascript">document.write(Base64.decode("MTA0LjI0OC4xMTUuMjM2"))</script>"John"</td>
我想得到“约翰”,但是我怎么得到呢?
你可以用BeautifulSoup做
如果<td>
有<script>
,则可以使用迭代器.children
并获取第二个/最后一个元素(第一个元素是<script>
)
from bs4 import BeautifulSoup as BS
html = '''<td style="text-align:center" class="left"><script
type="text/javascript">document.write(Base64.decode("MTA0LjI0OC4xMTUuMjM2"))</script>"John"</td>'''
soup = BS(html, 'html.parser')
td = soup.find('td')
text = list(td.children)[1]
print(text) # John
或者您可以找到<script>
并将其extract
出来,这样您的<td>
仅包含文本
from bs4 import BeautifulSoup as BS
html = '''<td style="text-align:center" class="left"><script
type="text/javascript">document.write(Base64.decode("MTA0LjI0OC4xMTUuMjM2"))</script>"John"</td>'''
soup = BS(html, 'html.parser')
td = soup.find('td')
td.find('script').extract()
text = td.text
print(td.text) # John
如果需要Base64.decode("MTA0LjI0OC4xMTUuMjM2")
文本,则可以找到<script>
并将其作为文本获取。 使用切片,您可以获取文本MTA0LjI0OC4xMTUuMjM2
并使用base64
模块进行解码。 您会收到文本104.248.115.236
from bs4 import BeautifulSoup as BS
import base64
html = '''<td style="text-align:center" class="left"><script
type="text/javascript">document.write(Base64.decode("MTA0LjI0OC4xMTUuMjM2"))</script>"John"</td>'''
soup = BS(html, 'html.parser')
td = soup.find('td')
script = td.find('script').text
text = script[30:-3]
text = base64.b64decode(text).decode()
print(text) # 104.248.115.236
您可以使用以下行获取文本。
table.find_element_by_xpath(".//td[@style='text-align:center']").text
确保。 xpath中有将范围限制为当前表节点的文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.