【问题标题】:How to scrape text between br tags如何在 br 标签之间抓取文本
【发布时间】:2014-11-18 21:21:11
【问题描述】:

我正在尝试抓取一个简单的网站http://hosted.where2getit.com/sharpsiica/index.html?form=locator_search&sku=ARM355&addressline=53203&zip=53203

我已尝试使用以下代码来抓取姓名和地址:

import lxml.html as lh    
from selenium import webdriver    
import time

browser = webdriver.Firefox()

browser.get('http://hosted.where2getit.com/sharpsiica/index.html?form=locator_search&sku=ARM355&addressline=53203&zip=53203')

time.sleep(5)

content = browser.page_source

tree = lh.fromstring(content)

name=tree.xpath('//table[@id="collection_poi"]/tbody/tr/td[@align="left"]/a/text()')

address=tree.xpath('//table[@id="collection_poi"]/tbody/tr/td[@align="left"]/text()')

print(name,address)

我得到了正确的名字,但是对于地址,我得到了太多不需要的数据。我只需要姓名和地址。

我哪里做错了?

【问题讨论】:

  • 如果selenium 本身基本上可以在页面上找到您想要的任何内容,为什么还需要lxml

标签: python selenium web web-scraping lxml


【解决方案1】:

剥离它 -

address=[c.strip() for c in address]

希望对您有所帮助。

但我只是想知道, 为什么要提取完整的地址和姓名列表? 难道你不想做类似的事情,

import lxml.html as lh
from selenium import webdriver
import time

browser = webdriver.Firefox()
browser.get('http://hosted.where2getit.com/sharpsiica/index.html?form=locator_search&sku=ARM355&addressline=53203&zip=53203')
time.sleep(5)
content = browser.page_source
tree = lh.fromstring(content)

for tr in tree.xpath('//*[@id="collection_poi"]//tr'):
    name=tr.xpath('.//*[@class="store_name"]//text()')
    name=[c.strip() for c in name]
    address=tr.xpath('.//*[@align="left"]//text()')
    address=[c.strip() for c in address]
    print(name,address)

您甚至可能想从获得的列表中删除空元素,

address=filter(None, address)
print address

希望有所帮助:-)

【讨论】:

    猜你喜欢
    • 2022-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-28
    • 2019-11-27
    相关资源
    最近更新 更多