gpt4 book ai didi

python-3.x - 从文本文件中读取多个 URL,处理每个网页,并抓取其中的内容

转载 作者:行者123 更新时间:2023-12-04 08:51:15 26 4
gpt4 key购买 nike

我有一个包含多个 URL 列表的 .txt 文件。我的目的是打开这个 .txt 文件,访问每一行中的每个 URL,抓取每个 URL 中的内容,并将 txt 文件中的多个 URL 列表的内容附加到“draft.csv”文件中。
当我尝试运行其他代码时,推荐请求结果显示“请打开JavaScript并刷新页面”,因此我打算使用Selenium来解决此问题。我能够根据需要获取所有页面,但无法在每个链接中看到所需的内容。
以下是多个 URL 的列表,例如:

http://example.com/2267/15175/index.html
http://example.com/2267/16796/index.html
http://example.com/2267/17895/index.html
这是我当前使用 Selenium 和 Requests 的代码。
from lxml import etree
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import sys
import pandas as pd
import urllib.request
import requests

frame =[]

chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
driver = webdriver.Chrome(options = chrome_options)

with open("draft.txt", "r") as file:
for line in file:
url = line.rstrip("\n")
print(url)

driver.get(url)
html = etree.HTML(driver.page_source)
allurl = requests.get(url)
htmltext = allurl.text

extract_link = html.xpath('//span[@id="my_two"]/table/tbody/tr/td/table[2]')
for i in extract_link:
link = i.xpath('./tbody/tr/td/div/p/a/@href')
content = 'http://example.com'+ link[0]

frame.append({
'content': content,
})

dfs = pd.DataFrame(frame)
dfs.to_csv('draft.csv',index=False,encoding='utf-8-sig')
预先感谢您帮助我解决这个问题!

最佳答案

您必须在 for 循环中加载 selenium,并且可以使用 bs4 进行抓取:

from selenium import webdriver
from bs4 import BeautifulSoup

f = open("urls.txt")
urls = [url.strip() for url in f.readlines()]
For url in urls:
driver.get(url)
...
html = driver.page_source
soup = BeautifulSoup(html)
Information = soup.find('title')
Url = url
...
driver.quit()

关于python-3.x - 从文本文件中读取多个 URL,处理每个网页,并抓取其中的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64091982/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com