我正在使用 Selenium 和 Python 从页面中提取信息
这是我想从中提取的 div:
<div class="_2v66">5</div>
Run Code Online (Sandbox Code Playgroud)
我想提取值“5”
这是我写的Python:
element = browser.find_elements_by_class_name('_2v66').getText
print('Views:')
print(element)
Run Code Online (Sandbox Code Playgroud)
当我运行此脚本时,我收到以下消息:
Traceback (most recent call last):
File "<string>", line 95, in <module>
AttributeError: 'list' object has no attribute 'getText'
[Finished in 15.478s]
Run Code Online (Sandbox Code Playgroud)
解决方案:
虽然我一开始认为div类是唯一的,但仔细查看页面后发现它不是一个唯一的div,因此解决方案如下:
browser.get(('https://www.facebook.com/example_page_1/insights/?section=navVideos'))
browser.implicitly_wait(60)
# find_elements_by_class_name - Returns the div in which the metrics are found
elements = browser.find_elements_by_class_name('_2v66')
for e in elements:
print(e.text)
Run Code Online (Sandbox Code Playgroud)
这browser.implicitly_wait对于允许页面加载至关重要。我收到的关于不存在的对象的错误就是因为这个。
我试图通过仅考虑某个子集来使用 Pandas.drop_duplicates() 但收到错误KeyError: Index(['days'], dtype='object')
指数如下:
id, event_description, attribute1, attribute 2, attribute 3, days, days_supply, days_equivalent
我想忽略属性 2 和属性 3 所以我运行了以下命令
df = df.drop_duplicates(subset=['id', 'event_description', 'attribute1', 'days', 'days_supply', 'days_equivalent'])
Run Code Online (Sandbox Code Playgroud)
返回:
eyError Traceback (most recent call last)
<ipython-input-4-3f7da32b380f> in <module>
7
8 df = df.drop_duplicates(subset=['id', 'event_description', 'attribute1', 'days',
-> 9 'days_supply', 'days_equivalent'])
10
11 print(df)
/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py in drop_duplicates(self, subset, keep, inplace)
4892
4893 inplace = validate_bool_kwarg(inplace, "inplace")
-> 4894 duplicated = self.duplicated(subset, keep=keep)
4895
4896 if inplace:
/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py in duplicated(self, …Run Code Online (Sandbox Code Playgroud) 我试图使用Python访问嵌套的JSON值.
这是我的JSON的摘录:
{
"data": [
{
"name": "page_video_views",
"period": "day",
"values": [
{
"value": 634,
"end_time": "2018-11-23T08:00:00+0000"
},
{
"value": 465,
"end_time": "2018-11-24T08:00:00+0000"
}
],
"title": "Daily Total Video Views",
"description": "Daily: Total number of times videos have been viewed for more than 3 seconds. (Total Count)",
"id": "{page-id}/insights/page_video_views/day"
},
Run Code Online (Sandbox Code Playgroud)
这是我到目前为止编写的代码:
import json
import urllib.request
data = urllib.request.urlopen("https://graph.facebook.com/v3.1/{page-id}/insights?access_token={access-token}&pretty=0&metric=page_impressions%2cpage_engaged_users%2cpage_fans%2cpage_video_views%2cpage_posts_impressions").read()
output = json.loads(data)
print(json.dumps(output, indent=2))
for item in output['data']:
name = item['name']
period = item['period']
value = item['data']['values']['value']
print(name, period, value)
Run Code Online (Sandbox Code Playgroud)
我面临的问题是,无论何时我运行代码来访问'name'和'period'它都能很好地工作,但是我无法访问'values'中的'value'.我相信这是因为有两个'价值'结果,我想每次拉第一个. …