python - Selenium 页面内容与 Google Chrome 开发工具不匹配
问题描述
我想从页面上抓取数据:https ://broward.county-taxes.com/public/real_estate/parcels/494101-09-1060/bills
有一张桌子,我需要:
- 获取表格的第一行
- 点击这个项目
- 刮取从价税部分(“TAXING AUTHORITY”和“MILLAGE”)数据
我已经使用 python selenium 实现了一个脚本,它在本地工作(linux mint 19)。当我部署到服务器并在服务器端(ubuntu)运行相同时,它不起作用
问题是,当我加载“账单”页面时,它根本不会加载任何表格和表格数据。我已经打印出driver.page_source并且表格丢失了。
任何建议将不胜感激。
下面是函数源代码。
奇怪的是它在本地可以工作,但在服务器端却不行!
def download_tax_bill_form(self, formatted_apn):
"""
Scrape county tax bill table by specified 'apn'
:param formatted_apn: The case apn formatted
Returns:
- scraped dictionary object
{
ad_valorem_taxes: [
{
'group_name': 'BROWARD COUNTY GOVERNMENT',
'items': [
{
'name': 'COUNTYWIDE SERVICES',
'millage': 5.49990
},
...
]
},
...
]
}
"""
if self.driver is None:
# create chrome driver
self.driver = self.create_driver()
# go to bills page by 'apn'
self.driver.get(f'https://broward.county-taxes.com/public/real_estate/parcels/{formatted_apn}/bills')
self.driver.implicitly_wait(5)
# click on the first table row (last year bill)
WebDriverWait(self.driver, 20).until(
EC.element_to_be_clickable(
(
By.XPATH,
"(//table[@class='table table-hover bills']/tbody)[1]/tr/th/a[1]"
)
)
).click()
# get table items from requested table
ad_valorem_taxes_items = self.driver.find_elements_by_xpath("//div[@class='row advalorem']/div/table/tbody")
groups = []
group = {}
# transform table results to dict
for item in ad_valorem_taxes_items:
class_name = item.get_attribute("class")
if class_name == 'district-group':
if group:
groups.append(group)
group = {}
group_name = item.find_element_by_xpath('.//tr/th').text
group["group_name"] = group_name
group["items"] = []
elif class_name == 'taxing-authority':
name = item.find_element_by_xpath(".//tr/th[@class='name']").text
try:
millage = float(item.find_element_by_xpath(".//tr/td[@class='millage']").text)
except ValueError:
millage = None
group_item = {
"name": name,
"millage": millage
}
group["items"].append(group_item)
# add last group
groups.append(group)
return {"ad_valorem_taxes": groups}
解决方案
我猜用户代理请求标头不同,因此页面显示不同的内容,您可以尝试在脚本中设置用户代理标头,类似于您的工作机器上的值
例如:
from selenium.webdriver.chrome.options import Options
opts = Options()
opts.add_argument('user-agent="Your user Agent Goes here!!"')
driver = webdriver.Chrome(chrome_options=opts)
您可以通过谷歌搜索“我的用户代理”或通过在浏览器中检查请求(“标头选项卡,请求标头,用户代理”)找到您的用户代理
推荐阅读
- r - 为什么当我单击任何脚注的上标时,它会将我带到文档的第一页而不是脚注?
- python-3.x - 熊猫申请 - 做同样的事情却有不同的结果?
- java - 解析嵌套 json 和更改响应结构时遇到问题
- cuda - Pycuda 在函数参数中按值声明数组时返回错误
- ios - 如何在 SceneKit 的渲染队列中处理触摸事件
- excel - Excel,从数组中返回唯一值值,但不返回空白值
- javascript - 脚本触发器不触发函数
- swift - SwiftUI 中未调用 Obj-C 函数
- timescaledb - timescaleDB 插入速度问题
- webrtc - Coturn 服务器给了 code=701 TURN allocate request timed out