Python 3.x 从一个文本文件中读取多个URL,处理每个网页,并从中删除内容

Python 3.x 从一个文本文件中读取多个URL,处理每个网页,并从中删除内容,python-3.x,selenium,selenium-webdriver,xpath,python-requests,Python 3.x,Selenium,Selenium Webdriver,Xpath,Python Requests,我有一个包含多个URL列表的.txt文件。我的目的是打开这个.txt文件,访问每行中的每个URL,刮取每个URL中的内容,并将包含txt文件中多个URL列表的内容附加到“draft.csv”文件中 当我尝试运行其他代码时,建议的请求结果显示“请打开JavaScript并刷新页面”,因此我打算使用Selenium来解决这个问题。我能够获取所需的所有页面,但无法在每个链接中看到所需的内容 下面是多个URL的列表,例如: http://example.com/2267/15175/index.html

我有一个包含多个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()

您的目的是使用子url浏览每个url,或者只是输入文件的每个url并提取其信息?@Dandal每个url的内容实际上是一个或多个子url。因此,我想从我从txt文件中获得的多个URL列表中删除这些子链接。希望你能帮我。非常感谢!谢谢你,丹达尔。我已经修改了你建议的一些代码,现在它工作起来很有魅力。祝你有美好的一天!