700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 常见的css选择器有 css元素定位工具 – CSS – 前端 htmlcss

常见的css选择器有 css元素定位工具 – CSS – 前端 htmlcss

时间:2023-02-15 09:03:21

相关推荐

常见的css选择器有 css元素定位工具 – CSS – 前端 htmlcss

下面罗列了一部分的CSS定位方式。看到这么多是否觉得CSS不再简单,其实不然常用的几种方式作者已标记,CSS定位是平常使用过程中非常重要的一种方式。它与Xpath定位有诸多类似的地方,但是无论从性能还是语法上来说CSS都是比较有优势的。

1、一般情况下定位速度要比XPATH快

2、语法比Xpath要简洁

用爬虫技术能做到哪些有趣的事情?

看到这个问题必须来怒答一波~用python爬虫爬便宜机票了解一下?

喜欢旅行又怕吃土?让Python来爬取最便宜机票吧!

图源:

你喜欢旅行吗?

这个问题通常会得到一个肯定的答案,随后引出一两个有关之前冒险经历的故事。大多数人都认为旅行是体验新文化和开阔视野的好方法。但如果问题是“你喜欢搜索机票的过程吗?”也许话题就到此为止了……

可事实上,便宜的机票往往也很重要!本文将尝试构建一个网络爬虫,该爬虫对特定目的地运行并执行带有浮动日期(首选日期前后最多三天)的航班价格搜索。它会将结果保存为excel文件并发送一封包含快速统计信息的电子邮件。显然,这个爬虫的目的就是帮助大家找到最优惠的价格!

你可以在服务器上运行脚本(一个简单的Raspberry Pi就可以),每天运行一到两次。结果会以邮件形式发送,建议将excel文件存入Dropbox文件夹,以便随时随地查看。

因为爬虫以“浮动日期”进行搜索,所以它会搜索首选日期前后最多三天的航班信息。尽管该脚本一次仅运行一对目的地,但可以很容易地改写该爬虫使其每个循环运行多个目的地。最终甚至可能找到一些错误票价…那会很有意思!

另一个爬虫

某种意义上来讲,网络爬取是互联网“工作”的核心。

也许你认为这是一个十分大胆的说法,但谷歌就是从拉里·佩奇用Java和Python构建的网络爬虫开始的。爬虫不断地爬取信息,整个互联网都在试图为所有问题提供最佳的可能答案。网络爬取有不计其数的应用程序,即使更喜欢数据科学中的其他分支,你仍需要一些爬取技巧以获得数据。

这里用到的一些技术来自于最近新的一本佳作《Python网络数据采集》,书中包含与网络爬取相关的所有内容,并提供了大量简例和实例。甚至有一个特别有意思的章节,讲述如何解决验证码检验的问题。

Python的拯救

第一个挑战就是选择爬取信息的平台,本文选择了客涯(Kayak)。大家试过了Momondo, 天巡(Skyscanner), 亿客行(Expedia)和其它一些网站,但是这些网站上的验证码特别变态。

在那些“你是人类吗?”的验证中,尝试了多次选择交通灯、十字路口和自行车后,客涯似乎是最好的选择,尽管短时间内加载太多页面它会跳出安全检查。

大家设法让机器人每4到6个小时查询一次网站,结果一切正常。虽然说不定哪个部分偶尔会出点小问题,但是如果收到验证码,既可以手动解决问题后启动机器人,也可以等待几小时后的自动重启。

如果你是网络爬取新手,或者不知道为何有些网站花费很大力气阻止网络爬取,那么为构建爬虫写下第一行代码前,你一定要多加努力。

谷歌的“网络爬取规范”:

/?q=web+scraping+etiquette

系紧安全带…

导入并打开Chrome浏览器标签页后,会定义一些循环中会用到的函数。这个架构的构思大概是这样的:

· 一个函数用于启动机器人程序,表明想要搜索的城市和日期。

· 这个函数获得首轮搜索结果,按“最佳”航班排序,然后点击“加载更多结果”。

· 另一个函数会爬取整个页面,并返回一个dataframe数据表。

· 随后重复步骤2和步骤3,得出按“价格”和“航行时间”排序的结果。

· 发送一封简要总结价格(最低价和平均价)的邮件,并将带有这三种排序类型的dataframe数据表保存为一份excel文件。

· 以上所有步骤会在循环中重复,每X小时运行一次。

每个Selenium项目都以一个网页驱动器开始。大家使用Chromedriver驱动器,但还有其它选择。PhantomJS和Firefox也很受欢迎。下载Chromedriver后,将其置于一个文件夹中即可。第一行代码会打开一个空白Chrome标签页。

from time import sleep, strftime

from random import randint

import pandas as pd

from selenium import webdriver

from mon.keys import Keys

import smtplib

from email.mime.multipart import MIMEMultipart

# Change this to your own chromedriver path!

chromedriver_path = ‘C:/{YOUR PATH HERE}/chromedriver_win32/chromedriver.exe’

driver = webdriver.Chrome(executable_path=chromedriver_path) # This will open the Chrome window

sleep(2)

这些是将用于整个项目的包。使用randint函数令机器人在每次搜索之间随机睡眠几秒钟。这对任何一个机器人来说都是必要属性。如果运行前面的代码,应该打开一个Chrome浏览器窗口,机器人会在其中导航。

一起来做一个快速测试:在另一个窗口上访问客涯网,选择往返城市和日期。选择日期时,确保选择的是“+-3天”。由于在编写代码时考虑到了结果页面,所以如果只想搜索特定日期,很可能需要做一些微小的调整。

点击搜索按钮在地址栏获取链接。它应该类似于下面所使用的链接,将变量kayak定义为url,并从网页驱动器执行get方法,搜索结果就会出现。

无论何时,只要在几分钟内使用get命令超过两到三次,就会出现验证码。实际上可以自己解决验证码,并在下一次验证出现时继续进行想要的测试。从测试来看,第一次搜索似乎一直没有问题,所以如果想运行这份代码,并让它在较长的时间间隔后运行,必须解决这个难题。你并不需要十分钟就更新一次这些价格,对吧?

每个XPath都有陷阱

到目前为止,已经打开了一个窗口,获取了一个网站。为了开始获取价格和其他信息,需要使用XPath或CSS选择器,大家选择了XPath。使用XPath导航网页可能会令人感到困惑,即使使用从inspector视图中直接使用“复制XPath”,但这不是获得所需元素的最佳方法。有时通过“复制XPath”这个方法获得的链接过于针对特定对象,以至于很快就失效了。《Python网络数据采集》一书很好地解释了使用XPath和CSS选择器导航的基础知识。

接下来,用Python选择最便宜的结果。上面代码中的红色文本是XPath选择器,在网页上任意一处右键单击选择“inspect”就可以看到它。在想要查看代码的位置,可以再次右键单击选择“inspect”。

为说明之前所观察到的从“inspector”复制路径的缺陷,请参考以下差异:

1 # This is what the copymethod would return. Right click highlighted rows on the right side and select “copy> Copy XPath”//*[@id=“wtKI-price_aTab”]/div[1]/div/div/div[1]/div/span/span

2 # This is what I used todefine the “Cheapest” buttoncheap_results= ‘//a[@data-code = “price”]’

第二种方法的简洁性清晰可见。它搜索具有data-code等于price属性的元素a。第一种方法查找id等于wtKI-price_aTab的元素,并遵循第一个div元素和另外四个div和两个span。这次……会成功的。现在就可以告诉你,id元素会在下次加载页面时更改。每次页面一加载,字母wtKI会动态改变,所以只要页面重新加载,代码就会失效。花些时间阅读XPath,保证你会有收获。

不过,使用复制的方法在不那么“复杂”的网站上工作,也是很好的!

基于以上所展示的内容,如果想在一个列表中以几个字符串的形式获得所有搜索结果该怎么办呢?其实很简单。每个结果都在一个对象中,这个对象的类是“resultWrapper”。获取所有结果可以通过像下面这样的for循环语句来实现。如果你能理解这一部分,应该可以理解接下来的大部分代码。它基本上指向想要的结果(结果包装器),使用某种方式(XPath)获得文本,并将其放置在可读对象中(首先使用flight_containers,然后使用flight_list)。

前三行已展示在图中,并且可以清楚地看到所需的内容,但是有获得信息的更优选择,需要逐一爬取每个元素。

准备起飞吧!

最容易编写的函数就是加载更多结果的函数,所以代码由此开始。为了在不触发安全验证的前提下最大化所获取的航班数量,每次页面显示后,单击“加载更多结果”。唯一的新内容就是所添加的try语句,因为有时按钮加载会出错。如果它对你也有用,只需在前面展示的start_kayak函数中进行简要注释。

# Load more results to maximize the scraping

def load_more():

try:

more_results = ‘//a[@class = “moreButton”]’

driver.find_element_by_xpath(more_results).click()

# Printing these notes during the program helps me quickly check what it is doing

print(‘sleeping…..’)

sleep(randint(45,60))

except:

pass

现在,经过这么长的介绍,已经准备好定义实际爬取页面的函数。

大家编译了下一个函数page_scrape中的大部分元素。有时这些元素会返回列表插入去程信息和返程信息之间。这里使用了一个简单的办法分开它们,比如在第一个 section_a_list和section_b_list变量中,该函数还返回一个flight_df数据表。所以可以分离在不同分类下得到的结果,之后再把它们合并起来。

def page_scrape():

“““This function takes care of the scraping part”““

xp_sections = ‘//*[@class=“section duration”]’

sections = driver.find_elements_by_xpath(xp_sections)

sections_list = [value.text for value in sections]

section_a_list = sections_list[::2] # This is to separate the two flights

section_b_list = sections_list[1::2] # This is to separate the two flights

# if you run into a reCaptcha, you might want to do something about it

# you will know there’s a problem if the lists above are empty

# this if statement lets you exit the bot or do something else

# you can add a sleep here, to let you solve the captcha and continue scraping

# i’m using a SystemExit because i want to test everything from the start

if section_a_list == []:

raise SystemExit

# I’ll use the letter A for the outbound flight and B for the inbound

a_duration = []

a_section_names = []

for n in section_a_list:

# Separate the time from the cities

a_section_names.append(”.join(n.split()[2:5]))

a_duration.append(”.join(n.split()[0:2]))

b_duration = []

b_section_names = []

for n in section_b_list:

# Separate the time from the cities

b_section_names.append(”.join(n.split()[2:5]))

b_duration.append(”.join(n.split()[0:2]))

xp_dates = ‘//div[@class=“section date”]’

dates = driver.find_elements_by_xpath(xp_dates)

dates_list = [value.text for value in dates]

a_date_list = dates_list[::2]

b_date_list = dates_list[1::2]

# Separating the weekday from the day

a_day = [value.split()[0] for value in a_date_list]

a_weekday = [value.split()[1] for value in a_date_list]

b_day = [value.split()[0] for value in b_date_list]

b_weekday = [value.split()[1] for value in b_date_list]

# getting the prices

xp_prices = ‘//a[@class=“booking-link”]/span[@class=“price option-text”]’

prices = driver.find_elements_by_xpath(xp_prices)

prices_list = [price.text.replace(‘$’,”) for price in prices if price.text != ”]

prices_list = list(map(int, prices_list))

# the stops are a big list with one leg on the even index and second leg on odd index

xp_stops = ‘//div[@class=“section stops”]/div[1]’

stops = driver.find_elements_by_xpath(xp_stops)

stops_list = [stop.text[0].replace(‘n’,’0′) for stop in stops]

a_stop_list = stops_list[::2]

b_stop_list = stops_list[1::2]

xp_stops_cities = ‘//div[@class=“section stops”]/div[2]’

stops_cities = driver.find_elements_by_xpath(xp_stops_cities)

stops_cities_list = [stop.text for stop in stops_cities]

a_stop_name_list = stops_cities_list[::2]

b_stop_name_list = stops_cities_list[1::2]

# this part gets me the airline company and the departure and arrival times, for both legs

xp_schedule = ‘//div[@class=“section times”]’

schedules = driver.find_elements_by_xpath(xp_schedule)

hours_list = []

carrier_list = []

for schedule in schedules:

hours_list.append(schedule.text.split(‘\n’)[0])

carrier_list.append(schedule.text.split(‘\n’)[1])

# split the hours and carriers, between a and b legs

a_hours = hours_list[::2]

a_carrier = carrier_list[1::2]

b_hours = hours_list[::2]

b_carrier = carrier_list[1::2]

cols = ([‘Out Day’, ‘Out Time’, ‘Out Weekday’, ‘Out Airline’, ‘Out Cities’, ‘Out Duration’, ‘Out Stops’, ‘Out Stop Cities’,

‘Return Day’, ‘Return Time’, ‘Return Weekday’, ‘Return Airline’, ‘Return Cities’, ‘Return Duration’, ‘Return Stops’, ‘Return Stop Cities’,

‘Price’])

flights_df = pd.DataFrame({‘Out Day’: a_day,

‘Out Weekday’: a_weekday,

‘Out Duration’: a_duration,

‘Out Cities’: a_section_names,

‘Return Day’: b_day,

‘Return Weekday’: b_weekday,

‘Return Duration’: b_duration,

‘Return Cities’: b_section_names,

‘Out Stops’: a_stop_list,

‘Out Stop Cities’: a_stop_name_list,

‘Return Stops’: b_stop_list,

‘Return Stop Cities’: b_stop_name_list,

‘Out Time’: a_hours,

‘Out Airline’: a_carrier,

‘Return Time’: b_hours,

‘Return Airline’: b_carrier,

‘Price’: prices_list})[cols]

flights_df[‘timestamp’] = strftime(“%Y%m%d-%H%M”) # so we can know when it was scraped

return flights_df

尽量让这些名字容易理解。记住变量a表示旅行的去程信息,变量b表示旅行的返程信息。接下来说说下一个函数。

等等,还有什么吗?

截至目前,已经有了一个能加载更多结果的函数和一个能爬取其他结果的函数。本可以在此结束这篇文章,而你可以自行手动使用这些函数,并在浏览的页面上使用爬取功能。但是前文提到给自己发送邮件和一些其他信息的内容,这都包含在接下来的函数start_kayak中。

它要求填入城市名和日期,并由此打开一个kayak字符串中的地址,该字符串直接跳转到“最佳”航班结果排序页面。第一次爬取后,可以获取价格的顶部矩阵,这个矩阵将用于计算平均值和最小值,之后和客涯(Kayak)的预测结果(页面左上角)一同发送到邮件中。这是单一日期搜索时可能导致错误的原因之一,因其不包含矩阵元素。

def start_kayak(city_from, city_to, date_start, date_end):

“““City codes – it’s the IATA codes!

Date format – YYYY-MM-DD”““

kayak = (‘/flights/’ + city_from + ‘-‘ + city_to +

‘/’ + date_start + ‘-flexible/’ + date_end + ‘-flexible?sort=bestflight_a’)

driver.get(kayak)

sleep(randint(8,10))

# sometimes a popup shows up, so we can use a try statement to check it and close

try:

xp_popup_close = ‘//button[contains(@id,”dialog-close”) and contains(@class,”Button-No-Standard-Style close “)]’

driver.find_elements_by_xpath(xp_popup_close)[5].click()

except Exception as e:

pass

sleep(randint(60,95))

print(‘loading more…..’)

#load_more()

print(‘starting first scrape…..’)

df_flights_best = page_scrape()

df_flights_best[‘sort’] = ‘best’

sleep(randint(60,80))

# Let’s also get the lowest prices from the matrix on top

matrix = driver.find_elements_by_xpath(‘//*[contains(@id,”FlexMatrixCell”)]’)

matrix_prices = [price.text.replace(‘$’,”) for price in matrix]

matrix_prices = list(map(int, matrix_prices))

matrix_min = min(matrix_prices)

matrix_avg = sum(matrix_prices)/len(matrix_prices)

print(‘switching to cheapest results…..’)

cheap_results = ‘//a[@data-code = “price”]’

driver.find_element_by_xpath(cheap_results).click()

sleep(randint(60,90))

print(‘loading more…..’)

#load_more()

print(‘starting second scrape…..’)

df_flights_cheap = page_scrape()

df_flights_cheap[‘sort’] = ‘cheap’

sleep(randint(60,80))

print(‘switching to quickest results…..’)

quick_results = ‘//a[@data-code = “duration”]’

driver.find_element_by_xpath(quick_results).click()

sleep(randint(60,90))

print(‘loading more…..’)

#load_more()

print(‘starting third scrape…..’)

df_flights_fast = page_scrape()

df_flights_fast[‘sort’] = ‘fast’

sleep(randint(60,80))

# saving a new dataframe as an excel file. the name is custom made to your cities and dates

final_df = df_flights_cheap.append(df_flights_best).append(df_flights_fast)

final_df.to_excel(‘search_backups//{}_flights_{}-{}_from_{}_to_{}.xlsx’.format(strftime(“%Y%m%d-%H%M”),

city_from, city_to,

date_start, date_end), index=False)

print(‘saved df…..’)

# We can keep track of what they predict and how it actually turns out!

xp_loading = ‘//div[contains(@id,”advice”)]’

loading = driver.find_element_by_xpath(xp_loading).text

xp_prediction = ‘//span[@class=“info-text”]’

prediction = driver.find_element_by_xpath(xp_prediction).text

print(loading+’\n’+prediction)

# sometimes we get this string in the loading variable, which will conflict with the email we send later

# just change it to “Not Sure” if it happens

weird = ‘¯\\_(ツ)_/¯’

if loading == weird:

loading = ‘Not sure’

username = ‘YOUREMAIL@’

password = ‘YOUR PASSWORD’

server = smtplib.SMTP(‘’, 587)

server.ehlo()

server.starttls()

server.login(username, password)

msg = (‘Subject: Flight Scraper\n\n\

Cheapest Flight: {}\nAverage Price: {}\n\nRecommendation: {}\n\nEnd of message’.format(matrix_min, matrix_avg, (loading+’\n’+prediction)))

message = MIMEMultipart()

message[‘From’] = ‘YOUREMAIL@’

message[‘to’] = ‘YOUROTHEREMAIL@’

server.sendmail(‘YOUREMAIL@’, ‘YOUROTHEREMAIL@’, msg)

print(‘sent email…..’)

虽然没有使用Gmail账户测试发送邮件,但是可以搜索到很多的替代方法,前文提到的那本书中也有其他方法来实现这一点。如果已有一个Hotmail账户,只要替换掉个人的详细信息,它就会开始工作了。

如果想探索脚本的某一部分正在做什么,可以将脚本复制下来并在函数外使用它。这是彻底理解它的唯一方法。

利用刚才创造的一切

在这些步骤之后,还可以想出一个简单的循环来使用刚创造的函数,同时使其持续运行。完成四个“花式”提示,写下城市和日期(输入)。因为测试时不想每次都输入这些变量,需要的时候可以使用以下这个清楚的方式进行替换。

如果已经做到了这一步,恭喜你!改进还有很多,比如与Twilio集成,发送文本消息而不是邮件。也可以使用VPN或更加难懂的方式同时从多个服务器上研究搜索结果。还有就是验证码的问题,验证码会时不时地跳出来,但对此类问题还是有解决办法的。不过,能走到这里已经是有很牢固的基础了,你可以尝试添加一些额外的要素。

使用脚本运行测试的示例

留言 点赞 关注

大家一起分享AI学习与发展的干货

欢迎关注全平台AI垂类自媒体 “读芯术”

css选择器识别范围?

css选择器优先级核心:每个选择器本身有优先级,作用范围越具体优先级越高。

CSS优先级从高到低分别是:

1.在属性后面使用 !important 会覆盖页面内任何位置定义的元素样式。

2.作为style属性写在元素标签上的内联样式

3.id选择器

4.类选择器

5.伪类选择器

6.属性选择器

7.标签选择器

8.通配符选择器

9.浏览器选择器

当CSS样式的规则由多个选择器组成时,id选择器的权值为1000,class选择器为100,标签选择器为10,按权值求和的记过高低决定哪个优先。当两个css规则的权值相同时,谁更具体用谁,也就是权值高的选择器作用的越具体优先级越高。当两个选择器规则和权值都是一样,后面样式会覆盖前面的!

css中为什么color添加颜色?

color意思就是颜色,所以可以前面加颜色后面加颜色代码。

CSS color颜色语法:

color:#000000;

Css样式中color后直接加RGB颜色值(#FFFFFF 、#000000 、#F00)

RGB颜色值在实际布局时候确定,可以使用Photoshop(简称PS)拾取工具进行获取获得。

三、两种方法设置对象颜色样式

1、在DIV标签内使用color颜色样式

<div ></div>

2、在CSS选择器中使用color颜色样式CSS代码:

.divcss5{color:#00F}

/* 设置对象divcss5内文字为蓝色 */

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。