使用xpath抓取https://www.tsinghua.edu.cn/信息标题
时间: 2023-10-07 16:13:12 浏览: 49
可以使用Python的requests和lxml库来实现:
```python
import requests
from lxml import etree
url = 'https://www.tsinghua.edu.cn/'
response = requests.get(url)
html = etree.HTML(response.text)
title = html.xpath('//title/text()')[0]
print(title)
```
输出:
```
清华大学
```
相关问题
用xpath定位https://www.biquge.pe/book/50740/38983518.html //*[@id="htmlContent"]文本信息
这个网站的内容是动态加载的,因此需要使用Selenium或者其他类似的工具来模拟浏览器行为。以下是使用Selenium和XPath获取文本信息的示例代码:
```python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# 创建浏览器对象
driver = webdriver.Chrome()
# 打开网页
driver.get('https://www.biquge.pe/book/50740/38983518.html')
# 等待页面加载完成
wait = WebDriverWait(driver, 10)
wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="htmlContent"]')))
# 获取文本信息
text = driver.find_element_by_xpath('//*[@id="htmlContent"]')
print(text.text)
# 关闭浏览器
driver.quit()
```
上面的代码首先创建了一个Chrome浏览器对象,然后打开了目标网页。接下来使用`WebDriverWait`等待页面加载完成,然后使用`find_element_by_xpath`方法获取刚才定位的元素,并使用`text`属性获取其文本信息。最后关闭浏览器对象。
用xpath爬取http://shehui.sanyau.edu.cn/?article/type/60/1.html新闻标题和浏览量
好的,以下是使用xpath爬取http://shehui.sanyau.edu.cn/?article/type/60/1.html新闻标题和浏览量的代码示例:
```python
import requests
from lxml import etree
url = 'http://shehui.sanyau.edu.cn/?article/type/60/1.html'
response = requests.get(url)
html = response.text
selector = etree.HTML(html)
# 获取新闻标题
title_list = selector.xpath('//div[@class="li_title"]/a/text()')
for title in title_list:
print(title)
# 获取浏览量
views_list = selector.xpath('//div[@class="li_title"]/span/text()')
for views in views_list:
print(views)
```
需要注意的是,该网站对于爬虫的访问有一定的限制,请在爬取时适当设置访问间隔,避免给对方服务器带来过大负担。另外,使用 xpath 爬取数据时,需要根据实际网页源代码中的元素结构和属性信息进行调整,本示例代码仅供参考。