如何使用Python构建打字机器人,以及进行Web抓取

众所周知,Python作为编程语言的一种,不仅语法简单、易学并且很有前途,很多人都对Python感兴趣。Python的应用十分广泛。经常关注我的朋友可能知道,关于Python的使用,之前已经为大家介绍了很多用法,今天主要介绍两个方面的内容,一个是如何使用Python构建打字机器人,另一是如何使用Python进行Web抓取的内容。

如何使用Python构建打字机器人,以及进行Web抓取_人工智能_机器人

 一、如何使用Python构建打字机器人

先决条件

pip install selenium

代码段

# Importing required modules and initializing variablesfrom selenium import webdriverfrom selenium.webdriver.common.action_chains import ActionChainsimport re

string = ''

# ______________________________________

# Opening thetypingcat.com on firefox

firefox = webdriver.Firefox()

firefox.get

# ______________________________________

# Using javascript to get the typing content from the website and storing value in "string" variablefor i in range(firefox.execute_script('return document.querySelectorAll(".line").length')):

string += firefox.execute_script('return document.querySelectorAll(".line")['+str(i)+'].innerHTML')

string = re.sub(r'<[^>]*>','',string) #This line is just delete tags present inside string

# ______________________________________

# Selenium commands to type what is stored inside string variable on the focused screen

action = ActionChains(firefox)

action.send_keys(string)

action.perform()

# ______________________________________ END ______________________________________

 二、如何使用Python进行Web抓取

仅需9行代码即可使用Python进行Web抓取。

先决条件

如果还没有安装,请安装beautifulsoup4和请求。

pip install beautifulsoup4

pip install requests

代码段

import requestsfrom bs4 import BeautifulSoup

result = requests.get

soup = BeautifulSoup(result.content)

links = soup.find_all("a", "title")

data = {}for link in links:

title = link.string

data[title] = link.attrs['href']

这里是完整的代码段,您可以将其直接复制并粘贴到终端,收藏的文本编辑器或jupyter笔记本中。

要检查您是否正确执行了该操作,数据输出应类似于以下内容:

{'MSI GL62VR 7RFX': '/test-sites/e-commerce/allinone/product/326',

'Dell Vostro 15…': '/test-sites/e-commerce/allinone/product/283',

'Dell Inspiron 17…': '/test-sites/e-commerce/allinone/product/296'}

Web抓取功能很棒,当您想从网站中快速提取数据时,可以节省大量时间。上面的示例可帮助您快速入门。

好了以上就是关于如何使用Python构建打字机器人,以及进行Web抓取的全部内容介绍,想了解更多关于Python的信息,请继续关注。

13
124
0
62

相关资讯

  1. 1、倪妮坐豪车拍写真,随性自然,网友:更喜欢优雅的赵丽颖2172
  2. 2、刘嘉玲首次公开谈论绑架案:原谅所有人,感谢没有被侵犯!1660
  3. 3、安妮斯顿新片落户Netflix将包含大量原创音乐4156
  4. 4、上半年新导演抢风头下半年大牌导演高调回击3840
  5. 5、知否:明兰的身边人里,唯独她的结局最好,怪不得说傻人有傻福3621
  6. 6、TVB花旦李施嬅晒与陈山聪父子合照,网友称:像极了一家三口717
  7. 7、冯绍峰结婚了,前女友各忙各的:林允亮相金鹰节,倪妮低调做公益905
  8. 8、她因长得丑被导演嫌弃,曾去相亲,如今嫁入豪门生活幸福1970
  9. 9、他们是因戏结缘的夫妻,婚后AA制惹热议,一家三口幸福成这样?2777
  10. 10、网友偶遇翟天临辛芷蕾逛迪士尼,被发现后两人从员工通道迅速逃离2270
全部评论(0)
我也有话说
0
收藏
点赞
顶部